es6.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.maximizeInPlace = function (other) {
  3784. if (other.x > this.x)
  3785. this.x = other.x;
  3786. if (other.y > this.y)
  3787. this.y = other.y;
  3788. if (other.z > this.z)
  3789. this.z = other.z;
  3790. if (other.w > this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5408. };
  5409. /**
  5410. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5442. };
  5443. /**
  5444. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5462. };
  5463. /**
  5464. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5484. };
  5485. /**
  5486. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * Wrapper class for promise with external resolve and reject.
  7120. */
  7121. var Deferred = /** @class */ (function () {
  7122. /**
  7123. * Constructor for this deferred object.
  7124. */
  7125. function Deferred() {
  7126. var _this = this;
  7127. this.promise = new Promise(function (resolve, reject) {
  7128. _this._resolve = resolve;
  7129. _this._reject = reject;
  7130. });
  7131. }
  7132. Object.defineProperty(Deferred.prototype, "resolve", {
  7133. /**
  7134. * The resolve method of the promise associated with this deferred object.
  7135. */
  7136. get: function () {
  7137. return this._resolve;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Deferred.prototype, "reject", {
  7143. /**
  7144. * The reject method of the promise associated with this deferred object.
  7145. */
  7146. get: function () {
  7147. return this._reject;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. return Deferred;
  7153. }());
  7154. BABYLON.Deferred = Deferred;
  7155. })(BABYLON || (BABYLON = {}));
  7156. //# sourceMappingURL=babylon.deferred.js.map
  7157. var BABYLON;
  7158. (function (BABYLON) {
  7159. /**
  7160. * A class serves as a medium between the observable and its observers
  7161. */
  7162. var EventState = /** @class */ (function () {
  7163. /**
  7164. * Create a new EventState
  7165. * @param mask defines the mask associated with this state
  7166. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7167. * @param target defines the original target of the state
  7168. * @param currentTarget defines the current target of the state
  7169. */
  7170. function EventState(mask, skipNextObservers, target, currentTarget) {
  7171. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7172. this.initalize(mask, skipNextObservers, target, currentTarget);
  7173. }
  7174. /**
  7175. * Initialize the current event state
  7176. * @param mask defines the mask associated with this state
  7177. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7178. * @param target defines the original target of the state
  7179. * @param currentTarget defines the current target of the state
  7180. * @returns the current event state
  7181. */
  7182. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7183. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7184. this.mask = mask;
  7185. this.skipNextObservers = skipNextObservers;
  7186. this.target = target;
  7187. this.currentTarget = currentTarget;
  7188. return this;
  7189. };
  7190. return EventState;
  7191. }());
  7192. BABYLON.EventState = EventState;
  7193. /**
  7194. * Represent an Observer registered to a given Observable object.
  7195. */
  7196. var Observer = /** @class */ (function () {
  7197. /**
  7198. * Creates a new observer
  7199. * @param callback defines the callback to call when the observer is notified
  7200. * @param mask defines the mask of the observer (used to filter notifications)
  7201. * @param scope defines the current scope used to restore the JS context
  7202. */
  7203. function Observer(
  7204. /**
  7205. * Defines the callback to call when the observer is notified
  7206. */
  7207. callback,
  7208. /**
  7209. * Defines the mask of the observer (used to filter notifications)
  7210. */
  7211. mask,
  7212. /**
  7213. * Defines the current scope used to restore the JS context
  7214. */
  7215. scope) {
  7216. if (scope === void 0) { scope = null; }
  7217. this.callback = callback;
  7218. this.mask = mask;
  7219. this.scope = scope;
  7220. /** @ignore */
  7221. this._willBeUnregistered = false;
  7222. /**
  7223. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7224. */
  7225. this.unregisterOnNextCall = false;
  7226. }
  7227. return Observer;
  7228. }());
  7229. BABYLON.Observer = Observer;
  7230. /**
  7231. * Represent a list of observers registered to multiple Observables object.
  7232. */
  7233. var MultiObserver = /** @class */ (function () {
  7234. function MultiObserver() {
  7235. }
  7236. /**
  7237. * Release associated resources
  7238. */
  7239. MultiObserver.prototype.dispose = function () {
  7240. if (this._observers && this._observables) {
  7241. for (var index = 0; index < this._observers.length; index++) {
  7242. this._observables[index].remove(this._observers[index]);
  7243. }
  7244. }
  7245. this._observers = null;
  7246. this._observables = null;
  7247. };
  7248. /**
  7249. * Raise a callback when one of the observable will notify
  7250. * @param observables defines a list of observables to watch
  7251. * @param callback defines the callback to call on notification
  7252. * @param mask defines the mask used to filter notifications
  7253. * @param scope defines the current scope used to restore the JS context
  7254. * @returns the new MultiObserver
  7255. */
  7256. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7257. if (mask === void 0) { mask = -1; }
  7258. if (scope === void 0) { scope = null; }
  7259. var result = new MultiObserver();
  7260. result._observers = new Array();
  7261. result._observables = observables;
  7262. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7263. var observable = observables_1[_i];
  7264. var observer = observable.add(callback, mask, false, scope);
  7265. if (observer) {
  7266. result._observers.push(observer);
  7267. }
  7268. }
  7269. return result;
  7270. };
  7271. return MultiObserver;
  7272. }());
  7273. BABYLON.MultiObserver = MultiObserver;
  7274. /**
  7275. * The Observable class is a simple implementation of the Observable pattern.
  7276. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7277. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7278. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7279. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7280. */
  7281. var Observable = /** @class */ (function () {
  7282. /**
  7283. * Creates a new observable
  7284. * @param onObserverAdded defines a callback to call when a new observer is added
  7285. */
  7286. function Observable(onObserverAdded) {
  7287. this._observers = new Array();
  7288. this._eventState = new EventState(0);
  7289. if (onObserverAdded) {
  7290. this._onObserverAdded = onObserverAdded;
  7291. }
  7292. }
  7293. /**
  7294. * Create a new Observer with the specified callback
  7295. * @param callback the callback that will be executed for that Observer
  7296. * @param mask the mask used to filter observers
  7297. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7298. * @param scope optional scope for the callback to be called from
  7299. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7300. * @returns the new observer created for the callback
  7301. */
  7302. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (insertFirst === void 0) { insertFirst = false; }
  7305. if (scope === void 0) { scope = null; }
  7306. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7307. if (!callback) {
  7308. return null;
  7309. }
  7310. var observer = new Observer(callback, mask, scope);
  7311. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7312. if (insertFirst) {
  7313. this._observers.unshift(observer);
  7314. }
  7315. else {
  7316. this._observers.push(observer);
  7317. }
  7318. if (this._onObserverAdded) {
  7319. this._onObserverAdded(observer);
  7320. }
  7321. return observer;
  7322. };
  7323. /**
  7324. * Remove an Observer from the Observable object
  7325. * @param observer the instance of the Observer to remove
  7326. * @returns false if it doesn't belong to this Observable
  7327. */
  7328. Observable.prototype.remove = function (observer) {
  7329. if (!observer) {
  7330. return false;
  7331. }
  7332. var index = this._observers.indexOf(observer);
  7333. if (index !== -1) {
  7334. this._observers.splice(index, 1);
  7335. return true;
  7336. }
  7337. return false;
  7338. };
  7339. /**
  7340. * Remove a callback from the Observable object
  7341. * @param callback the callback to remove
  7342. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7343. * @returns false if it doesn't belong to this Observable
  7344. */
  7345. Observable.prototype.removeCallback = function (callback, scope) {
  7346. for (var index = 0; index < this._observers.length; index++) {
  7347. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. }
  7352. return false;
  7353. };
  7354. Observable.prototype._deferUnregister = function (observer) {
  7355. var _this = this;
  7356. observer.unregisterOnNextCall = false;
  7357. observer._willBeUnregistered = true;
  7358. BABYLON.Tools.SetImmediate(function () {
  7359. _this.remove(observer);
  7360. });
  7361. };
  7362. /**
  7363. * Notify all Observers by calling their respective callback with the given data
  7364. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7365. * @param eventData defines the data to send to all observers
  7366. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7367. * @param target defines the original target of the state
  7368. * @param currentTarget defines the current target of the state
  7369. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7370. */
  7371. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7372. if (mask === void 0) { mask = -1; }
  7373. if (!this._observers.length) {
  7374. return true;
  7375. }
  7376. var state = this._eventState;
  7377. state.mask = mask;
  7378. state.target = target;
  7379. state.currentTarget = currentTarget;
  7380. state.skipNextObservers = false;
  7381. state.lastReturnValue = eventData;
  7382. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7383. var obs = _a[_i];
  7384. if (obs._willBeUnregistered) {
  7385. continue;
  7386. }
  7387. if (obs.mask & mask) {
  7388. if (obs.scope) {
  7389. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7390. }
  7391. else {
  7392. state.lastReturnValue = obs.callback(eventData, state);
  7393. }
  7394. if (obs.unregisterOnNextCall) {
  7395. this._deferUnregister(obs);
  7396. }
  7397. }
  7398. if (state.skipNextObservers) {
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. /**
  7405. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7406. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7407. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7408. * and it is crucial that all callbacks will be executed.
  7409. * The order of the callbacks is kept, callbacks are not executed parallel.
  7410. *
  7411. * @param eventData The data to be sent to each callback
  7412. * @param mask is used to filter observers defaults to -1
  7413. * @param target defines the callback target (see EventState)
  7414. * @param currentTarget defines he current object in the bubbling phase
  7415. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7416. */
  7417. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7418. var _this = this;
  7419. if (mask === void 0) { mask = -1; }
  7420. // create an empty promise
  7421. var p = Promise.resolve(eventData);
  7422. // no observers? return this promise.
  7423. if (!this._observers.length) {
  7424. return p;
  7425. }
  7426. var state = this._eventState;
  7427. state.mask = mask;
  7428. state.target = target;
  7429. state.currentTarget = currentTarget;
  7430. state.skipNextObservers = false;
  7431. // execute one callback after another (not using Promise.all, the order is important)
  7432. this._observers.forEach(function (obs) {
  7433. if (state.skipNextObservers) {
  7434. return;
  7435. }
  7436. if (obs._willBeUnregistered) {
  7437. return;
  7438. }
  7439. if (obs.mask & mask) {
  7440. if (obs.scope) {
  7441. p = p.then(function (lastReturnedValue) {
  7442. state.lastReturnValue = lastReturnedValue;
  7443. return obs.callback.apply(obs.scope, [eventData, state]);
  7444. });
  7445. }
  7446. else {
  7447. p = p.then(function (lastReturnedValue) {
  7448. state.lastReturnValue = lastReturnedValue;
  7449. return obs.callback(eventData, state);
  7450. });
  7451. }
  7452. if (obs.unregisterOnNextCall) {
  7453. _this._deferUnregister(obs);
  7454. }
  7455. }
  7456. });
  7457. // return the eventData
  7458. return p.then(function () { return eventData; });
  7459. };
  7460. /**
  7461. * Notify a specific observer
  7462. * @param observer defines the observer to notify
  7463. * @param eventData defines the data to be sent to each callback
  7464. * @param mask is used to filter observers defaults to -1
  7465. */
  7466. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7467. if (mask === void 0) { mask = -1; }
  7468. var state = this._eventState;
  7469. state.mask = mask;
  7470. state.skipNextObservers = false;
  7471. observer.callback(eventData, state);
  7472. };
  7473. /**
  7474. * Gets a boolean indicating if the observable has at least one observer
  7475. * @returns true is the Observable has at least one Observer registered
  7476. */
  7477. Observable.prototype.hasObservers = function () {
  7478. return this._observers.length > 0;
  7479. };
  7480. /**
  7481. * Clear the list of observers
  7482. */
  7483. Observable.prototype.clear = function () {
  7484. this._observers = new Array();
  7485. this._onObserverAdded = null;
  7486. };
  7487. /**
  7488. * Clone the current observable
  7489. * @returns a new observable
  7490. */
  7491. Observable.prototype.clone = function () {
  7492. var result = new Observable();
  7493. result._observers = this._observers.slice(0);
  7494. return result;
  7495. };
  7496. /**
  7497. * Does this observable handles observer registered with a given mask
  7498. * @param mask defines the mask to be tested
  7499. * @return whether or not one observer registered with the given mask is handeled
  7500. **/
  7501. Observable.prototype.hasSpecificMask = function (mask) {
  7502. if (mask === void 0) { mask = -1; }
  7503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7504. var obs = _a[_i];
  7505. if (obs.mask & mask || obs.mask === mask) {
  7506. return true;
  7507. }
  7508. }
  7509. return false;
  7510. };
  7511. return Observable;
  7512. }());
  7513. BABYLON.Observable = Observable;
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.observable.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var SmartArray = /** @class */ (function () {
  7519. function SmartArray(capacity) {
  7520. this.length = 0;
  7521. this.data = new Array(capacity);
  7522. this._id = SmartArray._GlobalId++;
  7523. }
  7524. SmartArray.prototype.push = function (value) {
  7525. this.data[this.length++] = value;
  7526. if (this.length > this.data.length) {
  7527. this.data.length *= 2;
  7528. }
  7529. };
  7530. SmartArray.prototype.forEach = function (func) {
  7531. for (var index = 0; index < this.length; index++) {
  7532. func(this.data[index]);
  7533. }
  7534. };
  7535. SmartArray.prototype.sort = function (compareFn) {
  7536. this.data.sort(compareFn);
  7537. };
  7538. SmartArray.prototype.reset = function () {
  7539. this.length = 0;
  7540. };
  7541. SmartArray.prototype.dispose = function () {
  7542. this.reset();
  7543. if (this.data) {
  7544. this.data.length = 0;
  7545. this.data = [];
  7546. }
  7547. };
  7548. SmartArray.prototype.concat = function (array) {
  7549. if (array.length === 0) {
  7550. return;
  7551. }
  7552. if (this.length + array.length > this.data.length) {
  7553. this.data.length = (this.length + array.length) * 2;
  7554. }
  7555. for (var index = 0; index < array.length; index++) {
  7556. this.data[this.length++] = (array.data || array)[index];
  7557. }
  7558. };
  7559. SmartArray.prototype.indexOf = function (value) {
  7560. var position = this.data.indexOf(value);
  7561. if (position >= this.length) {
  7562. return -1;
  7563. }
  7564. return position;
  7565. };
  7566. SmartArray.prototype.contains = function (value) {
  7567. return this.data.indexOf(value) !== -1;
  7568. };
  7569. // Statics
  7570. SmartArray._GlobalId = 0;
  7571. return SmartArray;
  7572. }());
  7573. BABYLON.SmartArray = SmartArray;
  7574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7575. __extends(SmartArrayNoDuplicate, _super);
  7576. function SmartArrayNoDuplicate() {
  7577. var _this = _super !== null && _super.apply(this, arguments) || this;
  7578. _this._duplicateId = 0;
  7579. return _this;
  7580. }
  7581. SmartArrayNoDuplicate.prototype.push = function (value) {
  7582. _super.prototype.push.call(this, value);
  7583. if (!value.__smartArrayFlags) {
  7584. value.__smartArrayFlags = {};
  7585. }
  7586. value.__smartArrayFlags[this._id] = this._duplicateId;
  7587. };
  7588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7590. return false;
  7591. }
  7592. this.push(value);
  7593. return true;
  7594. };
  7595. SmartArrayNoDuplicate.prototype.reset = function () {
  7596. _super.prototype.reset.call(this);
  7597. this._duplicateId++;
  7598. };
  7599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7600. if (array.length === 0) {
  7601. return;
  7602. }
  7603. if (this.length + array.length > this.data.length) {
  7604. this.data.length = (this.length + array.length) * 2;
  7605. }
  7606. for (var index = 0; index < array.length; index++) {
  7607. var item = (array.data || array)[index];
  7608. this.pushNoDuplicate(item);
  7609. }
  7610. };
  7611. return SmartArrayNoDuplicate;
  7612. }(SmartArray));
  7613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7614. })(BABYLON || (BABYLON = {}));
  7615. //# sourceMappingURL=babylon.smartArray.js.map
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7620. var LoadFileError = /** @class */ (function (_super) {
  7621. __extends(LoadFileError, _super);
  7622. function LoadFileError(message, request) {
  7623. var _this = _super.call(this, message) || this;
  7624. _this.request = request;
  7625. _this.name = "LoadFileError";
  7626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7627. return _this;
  7628. }
  7629. // Polyfill for Object.setPrototypeOf if necessary.
  7630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7631. return LoadFileError;
  7632. }(Error));
  7633. BABYLON.LoadFileError = LoadFileError;
  7634. var RetryStrategy = /** @class */ (function () {
  7635. function RetryStrategy() {
  7636. }
  7637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7638. if (maxRetries === void 0) { maxRetries = 3; }
  7639. if (baseInterval === void 0) { baseInterval = 500; }
  7640. return function (url, request, retryIndex) {
  7641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7642. return -1;
  7643. }
  7644. return Math.pow(2, retryIndex) * baseInterval;
  7645. };
  7646. };
  7647. return RetryStrategy;
  7648. }());
  7649. BABYLON.RetryStrategy = RetryStrategy;
  7650. // Screenshots
  7651. var screenshotCanvas;
  7652. var cloneValue = function (source, destinationObject) {
  7653. if (!source)
  7654. return null;
  7655. if (source instanceof BABYLON.Mesh) {
  7656. return null;
  7657. }
  7658. if (source instanceof BABYLON.SubMesh) {
  7659. return source.clone(destinationObject);
  7660. }
  7661. else if (source.clone) {
  7662. return source.clone();
  7663. }
  7664. return null;
  7665. };
  7666. var Tools = /** @class */ (function () {
  7667. function Tools() {
  7668. }
  7669. /**
  7670. * Interpolates between a and b via alpha
  7671. * @param a The lower value (returned when alpha = 0)
  7672. * @param b The upper value (returned when alpha = 1)
  7673. * @param alpha The interpolation-factor
  7674. * @return The mixed value
  7675. */
  7676. Tools.Mix = function (a, b, alpha) {
  7677. return a * (1 - alpha) + b * alpha;
  7678. };
  7679. Tools.Instantiate = function (className) {
  7680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7681. return Tools.RegisteredExternalClasses[className];
  7682. }
  7683. var arr = className.split(".");
  7684. var fn = (window || this);
  7685. for (var i = 0, len = arr.length; i < len; i++) {
  7686. fn = fn[arr[i]];
  7687. }
  7688. if (typeof fn !== "function") {
  7689. return null;
  7690. }
  7691. return fn;
  7692. };
  7693. /**
  7694. * Provides a slice function that will work even on IE
  7695. * @param data defines the array to slice
  7696. * @returns the new sliced array
  7697. */
  7698. Tools.Slice = function (data) {
  7699. if (data.slice) {
  7700. return data.slice();
  7701. }
  7702. return Array.prototype.slice.call(data);
  7703. };
  7704. Tools.SetImmediate = function (action) {
  7705. if (window.setImmediate) {
  7706. window.setImmediate(action);
  7707. }
  7708. else {
  7709. setTimeout(action, 1);
  7710. }
  7711. };
  7712. Tools.IsExponentOfTwo = function (value) {
  7713. var count = 1;
  7714. do {
  7715. count *= 2;
  7716. } while (count < value);
  7717. return count === value;
  7718. };
  7719. /**
  7720. * Find the next highest power of two.
  7721. * @param x Number to start search from.
  7722. * @return Next highest power of two.
  7723. */
  7724. Tools.CeilingPOT = function (x) {
  7725. x--;
  7726. x |= x >> 1;
  7727. x |= x >> 2;
  7728. x |= x >> 4;
  7729. x |= x >> 8;
  7730. x |= x >> 16;
  7731. x++;
  7732. return x;
  7733. };
  7734. /**
  7735. * Find the next lowest power of two.
  7736. * @param x Number to start search from.
  7737. * @return Next lowest power of two.
  7738. */
  7739. Tools.FloorPOT = function (x) {
  7740. x = x | (x >> 1);
  7741. x = x | (x >> 2);
  7742. x = x | (x >> 4);
  7743. x = x | (x >> 8);
  7744. x = x | (x >> 16);
  7745. return x - (x >> 1);
  7746. };
  7747. /**
  7748. * Find the nearest power of two.
  7749. * @param x Number to start search from.
  7750. * @return Next nearest power of two.
  7751. */
  7752. Tools.NearestPOT = function (x) {
  7753. var c = Tools.CeilingPOT(x);
  7754. var f = Tools.FloorPOT(x);
  7755. return (c - x) > (x - f) ? f : c;
  7756. };
  7757. Tools.GetExponentOfTwo = function (value, max, mode) {
  7758. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7759. var pot;
  7760. switch (mode) {
  7761. case BABYLON.Engine.SCALEMODE_FLOOR:
  7762. pot = Tools.FloorPOT(value);
  7763. break;
  7764. case BABYLON.Engine.SCALEMODE_NEAREST:
  7765. pot = Tools.NearestPOT(value);
  7766. break;
  7767. case BABYLON.Engine.SCALEMODE_CEILING:
  7768. default:
  7769. pot = Tools.CeilingPOT(value);
  7770. break;
  7771. }
  7772. return Math.min(pot, max);
  7773. };
  7774. Tools.GetFilename = function (path) {
  7775. var index = path.lastIndexOf("/");
  7776. if (index < 0)
  7777. return path;
  7778. return path.substring(index + 1);
  7779. };
  7780. /**
  7781. * Extracts the "folder" part of a path (everything before the filename).
  7782. * @param uri The URI to extract the info from
  7783. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7784. * @returns The "folder" part of the path
  7785. */
  7786. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7787. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7788. var index = uri.lastIndexOf("/");
  7789. if (index < 0) {
  7790. if (returnUnchangedIfNoSlash) {
  7791. return uri;
  7792. }
  7793. return "";
  7794. }
  7795. return uri.substring(0, index + 1);
  7796. };
  7797. Tools.GetDOMTextContent = function (element) {
  7798. var result = "";
  7799. var child = element.firstChild;
  7800. while (child) {
  7801. if (child.nodeType === 3) {
  7802. result += child.textContent;
  7803. }
  7804. child = child.nextSibling;
  7805. }
  7806. return result;
  7807. };
  7808. Tools.ToDegrees = function (angle) {
  7809. return angle * 180 / Math.PI;
  7810. };
  7811. Tools.ToRadians = function (angle) {
  7812. return angle * Math.PI / 180;
  7813. };
  7814. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7815. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7816. var output = "";
  7817. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7818. var i = 0;
  7819. var bytes = new Uint8Array(buffer);
  7820. while (i < bytes.length) {
  7821. chr1 = bytes[i++];
  7822. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7823. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7824. enc1 = chr1 >> 2;
  7825. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7826. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7827. enc4 = chr3 & 63;
  7828. if (isNaN(chr2)) {
  7829. enc3 = enc4 = 64;
  7830. }
  7831. else if (isNaN(chr3)) {
  7832. enc4 = 64;
  7833. }
  7834. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7835. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7836. }
  7837. return "data:image/png;base64," + output;
  7838. };
  7839. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7840. if (bias === void 0) { bias = null; }
  7841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7843. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7844. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7847. }
  7848. if (bias) {
  7849. minimum.x -= minimum.x * bias.x + bias.y;
  7850. minimum.y -= minimum.y * bias.x + bias.y;
  7851. minimum.z -= minimum.z * bias.x + bias.y;
  7852. maximum.x += maximum.x * bias.x + bias.y;
  7853. maximum.y += maximum.y * bias.x + bias.y;
  7854. maximum.z += maximum.z * bias.x + bias.y;
  7855. }
  7856. return {
  7857. minimum: minimum,
  7858. maximum: maximum
  7859. };
  7860. };
  7861. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7862. if (bias === void 0) { bias = null; }
  7863. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7864. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7865. if (!stride) {
  7866. stride = 3;
  7867. }
  7868. for (var index = start; index < start + count; index++) {
  7869. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7870. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7871. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7872. }
  7873. if (bias) {
  7874. minimum.x -= minimum.x * bias.x + bias.y;
  7875. minimum.y -= minimum.y * bias.x + bias.y;
  7876. minimum.z -= minimum.z * bias.x + bias.y;
  7877. maximum.x += maximum.x * bias.x + bias.y;
  7878. maximum.y += maximum.y * bias.x + bias.y;
  7879. maximum.z += maximum.z * bias.x + bias.y;
  7880. }
  7881. return {
  7882. minimum: minimum,
  7883. maximum: maximum
  7884. };
  7885. };
  7886. Tools.Vector2ArrayFeeder = function (array) {
  7887. return function (index) {
  7888. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7889. var length = isFloatArray ? array.length / 2 : array.length;
  7890. if (index >= length) {
  7891. return null;
  7892. }
  7893. if (isFloatArray) {
  7894. var fa = array;
  7895. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7896. }
  7897. var a = array;
  7898. return a[index];
  7899. };
  7900. };
  7901. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7902. if (bias === void 0) { bias = null; }
  7903. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7904. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7905. var i = 0;
  7906. var cur = feeder(i++);
  7907. while (cur) {
  7908. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7909. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7910. cur = feeder(i++);
  7911. }
  7912. if (bias) {
  7913. minimum.x -= minimum.x * bias.x + bias.y;
  7914. minimum.y -= minimum.y * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. }
  7918. return {
  7919. minimum: minimum,
  7920. maximum: maximum
  7921. };
  7922. };
  7923. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7924. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7925. return null;
  7926. return Array.isArray(obj) ? obj : [obj];
  7927. };
  7928. // Misc.
  7929. Tools.GetPointerPrefix = function () {
  7930. var eventPrefix = "pointer";
  7931. // Check if pointer events are supported
  7932. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7933. eventPrefix = "mouse";
  7934. }
  7935. return eventPrefix;
  7936. };
  7937. /**
  7938. * @param func - the function to be called
  7939. * @param requester - the object that will request the next frame. Falls back to window.
  7940. */
  7941. Tools.QueueNewFrame = function (func, requester) {
  7942. if (!Tools.IsWindowObjectExist()) {
  7943. return setTimeout(func, 16);
  7944. }
  7945. if (!requester) {
  7946. requester = window;
  7947. }
  7948. if (requester.requestAnimationFrame) {
  7949. return requester.requestAnimationFrame(func);
  7950. }
  7951. else if (requester.msRequestAnimationFrame) {
  7952. return requester.msRequestAnimationFrame(func);
  7953. }
  7954. else if (requester.webkitRequestAnimationFrame) {
  7955. return requester.webkitRequestAnimationFrame(func);
  7956. }
  7957. else if (requester.mozRequestAnimationFrame) {
  7958. return requester.mozRequestAnimationFrame(func);
  7959. }
  7960. else if (requester.oRequestAnimationFrame) {
  7961. return requester.oRequestAnimationFrame(func);
  7962. }
  7963. else {
  7964. return window.setTimeout(func, 16);
  7965. }
  7966. };
  7967. Tools.RequestFullscreen = function (element) {
  7968. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7969. if (!requestFunction)
  7970. return;
  7971. requestFunction.call(element);
  7972. };
  7973. Tools.ExitFullscreen = function () {
  7974. if (document.exitFullscreen) {
  7975. document.exitFullscreen();
  7976. }
  7977. else if (document.mozCancelFullScreen) {
  7978. document.mozCancelFullScreen();
  7979. }
  7980. else if (document.webkitCancelFullScreen) {
  7981. document.webkitCancelFullScreen();
  7982. }
  7983. else if (document.msCancelFullScreen) {
  7984. document.msCancelFullScreen();
  7985. }
  7986. };
  7987. Tools.SetCorsBehavior = function (url, element) {
  7988. if (url && url.indexOf("data:") === 0) {
  7989. return;
  7990. }
  7991. if (Tools.CorsBehavior) {
  7992. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7993. element.crossOrigin = Tools.CorsBehavior;
  7994. }
  7995. else {
  7996. var result = Tools.CorsBehavior(url);
  7997. if (result) {
  7998. element.crossOrigin = result;
  7999. }
  8000. }
  8001. }
  8002. };
  8003. // External files
  8004. Tools.CleanUrl = function (url) {
  8005. url = url.replace(/#/mg, "%23");
  8006. return url;
  8007. };
  8008. Tools.LoadImage = function (url, onLoad, onError, database) {
  8009. if (url instanceof ArrayBuffer) {
  8010. url = Tools.EncodeArrayBufferTobase64(url);
  8011. }
  8012. url = Tools.CleanUrl(url);
  8013. url = Tools.PreprocessUrl(url);
  8014. var img = new Image();
  8015. Tools.SetCorsBehavior(url, img);
  8016. var loadHandler = function () {
  8017. img.removeEventListener("load", loadHandler);
  8018. img.removeEventListener("error", errorHandler);
  8019. onLoad(img);
  8020. };
  8021. var errorHandler = function (err) {
  8022. img.removeEventListener("load", loadHandler);
  8023. img.removeEventListener("error", errorHandler);
  8024. Tools.Error("Error while trying to load image: " + url);
  8025. if (onError) {
  8026. onError("Error while trying to load image: " + url, err);
  8027. }
  8028. };
  8029. img.addEventListener("load", loadHandler);
  8030. img.addEventListener("error", errorHandler);
  8031. var noIndexedDB = function () {
  8032. img.src = url;
  8033. };
  8034. var loadFromIndexedDB = function () {
  8035. if (database) {
  8036. database.loadImageFromDB(url, img);
  8037. }
  8038. };
  8039. //ANY database to do!
  8040. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8041. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8042. }
  8043. else {
  8044. if (url.indexOf("file:") !== -1) {
  8045. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8046. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8047. try {
  8048. var blobURL;
  8049. try {
  8050. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8051. }
  8052. catch (ex) {
  8053. // Chrome doesn't support oneTimeOnly parameter
  8054. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8055. }
  8056. img.src = blobURL;
  8057. }
  8058. catch (e) {
  8059. img.src = "";
  8060. }
  8061. return img;
  8062. }
  8063. }
  8064. noIndexedDB();
  8065. }
  8066. return img;
  8067. };
  8068. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8069. url = Tools.CleanUrl(url);
  8070. url = Tools.PreprocessUrl(url);
  8071. // If file and file input are set
  8072. if (url.indexOf("file:") !== -1) {
  8073. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8074. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8075. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8076. }
  8077. }
  8078. var loadUrl = Tools.BaseUrl + url;
  8079. var aborted = false;
  8080. var fileRequest = {
  8081. onCompleteObservable: new BABYLON.Observable(),
  8082. abort: function () { return aborted = true; },
  8083. };
  8084. var requestFile = function () {
  8085. var request = new XMLHttpRequest();
  8086. var retryHandle = null;
  8087. fileRequest.abort = function () {
  8088. aborted = true;
  8089. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8090. request.abort();
  8091. }
  8092. if (retryHandle !== null) {
  8093. clearTimeout(retryHandle);
  8094. retryHandle = null;
  8095. }
  8096. };
  8097. var retryLoop = function (retryIndex) {
  8098. request.open('GET', loadUrl, true);
  8099. if (useArrayBuffer) {
  8100. request.responseType = "arraybuffer";
  8101. }
  8102. if (onProgress) {
  8103. request.addEventListener("progress", onProgress);
  8104. }
  8105. var onLoadEnd = function () {
  8106. request.removeEventListener("loadend", onLoadEnd);
  8107. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8108. fileRequest.onCompleteObservable.clear();
  8109. };
  8110. request.addEventListener("loadend", onLoadEnd);
  8111. var onReadyStateChange = function () {
  8112. if (aborted) {
  8113. return;
  8114. }
  8115. // In case of undefined state in some browsers.
  8116. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8117. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8118. request.removeEventListener("readystatechange", onReadyStateChange);
  8119. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8120. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8121. return;
  8122. }
  8123. var retryStrategy = Tools.DefaultRetryStrategy;
  8124. if (retryStrategy) {
  8125. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8126. if (waitTime !== -1) {
  8127. // Prevent the request from completing for retry.
  8128. request.removeEventListener("loadend", onLoadEnd);
  8129. request = new XMLHttpRequest();
  8130. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8131. return;
  8132. }
  8133. }
  8134. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8135. if (onError) {
  8136. onError(request, e);
  8137. }
  8138. else {
  8139. throw e;
  8140. }
  8141. }
  8142. };
  8143. request.addEventListener("readystatechange", onReadyStateChange);
  8144. request.send();
  8145. };
  8146. retryLoop(0);
  8147. };
  8148. // Caching all files
  8149. if (database && database.enableSceneOffline) {
  8150. var noIndexedDB_1 = function () {
  8151. if (!aborted) {
  8152. requestFile();
  8153. }
  8154. };
  8155. var loadFromIndexedDB = function () {
  8156. // TODO: database needs to support aborting and should return a IFileRequest
  8157. if (aborted) {
  8158. return;
  8159. }
  8160. if (database) {
  8161. database.loadFileFromDB(url, function (data) {
  8162. if (!aborted) {
  8163. onSuccess(data);
  8164. }
  8165. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8166. }, onProgress ? function (event) {
  8167. if (!aborted) {
  8168. onProgress(event);
  8169. }
  8170. } : undefined, noIndexedDB_1, useArrayBuffer);
  8171. }
  8172. };
  8173. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8174. }
  8175. else {
  8176. requestFile();
  8177. }
  8178. return fileRequest;
  8179. };
  8180. /**
  8181. * Load a script (identified by an url). When the url returns, the
  8182. * content of this file is added into a new script element, attached to the DOM (body element)
  8183. */
  8184. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8185. var head = document.getElementsByTagName('head')[0];
  8186. var script = document.createElement('script');
  8187. script.type = 'text/javascript';
  8188. script.src = scriptUrl;
  8189. script.onload = function () {
  8190. if (onSuccess) {
  8191. onSuccess();
  8192. }
  8193. };
  8194. script.onerror = function (e) {
  8195. if (onError) {
  8196. onError("Unable to load script", e);
  8197. }
  8198. };
  8199. head.appendChild(script);
  8200. };
  8201. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8202. var reader = new FileReader();
  8203. var request = {
  8204. onCompleteObservable: new BABYLON.Observable(),
  8205. abort: function () { return reader.abort(); },
  8206. };
  8207. reader.onloadend = function (e) {
  8208. request.onCompleteObservable.notifyObservers(request);
  8209. };
  8210. reader.onload = function (e) {
  8211. //target doesn't have result from ts 1.3
  8212. callback(e.target['result']);
  8213. };
  8214. reader.onprogress = progressCallback;
  8215. reader.readAsDataURL(fileToLoad);
  8216. return request;
  8217. };
  8218. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8219. var reader = new FileReader();
  8220. var request = {
  8221. onCompleteObservable: new BABYLON.Observable(),
  8222. abort: function () { return reader.abort(); },
  8223. };
  8224. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8225. reader.onerror = function (e) {
  8226. Tools.Log("Error while reading file: " + fileToLoad.name);
  8227. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8228. };
  8229. reader.onload = function (e) {
  8230. //target doesn't have result from ts 1.3
  8231. callback(e.target['result']);
  8232. };
  8233. if (progressCallBack) {
  8234. reader.onprogress = progressCallBack;
  8235. }
  8236. if (!useArrayBuffer) {
  8237. // Asynchronous read
  8238. reader.readAsText(fileToLoad);
  8239. }
  8240. else {
  8241. reader.readAsArrayBuffer(fileToLoad);
  8242. }
  8243. return request;
  8244. };
  8245. //returns a downloadable url to a file content.
  8246. Tools.FileAsURL = function (content) {
  8247. var fileBlob = new Blob([content]);
  8248. var url = window.URL || window.webkitURL;
  8249. var link = url.createObjectURL(fileBlob);
  8250. return link;
  8251. };
  8252. // Misc.
  8253. Tools.Format = function (value, decimals) {
  8254. if (decimals === void 0) { decimals = 2; }
  8255. return value.toFixed(decimals);
  8256. };
  8257. Tools.CheckExtends = function (v, min, max) {
  8258. if (v.x < min.x)
  8259. min.x = v.x;
  8260. if (v.y < min.y)
  8261. min.y = v.y;
  8262. if (v.z < min.z)
  8263. min.z = v.z;
  8264. if (v.x > max.x)
  8265. max.x = v.x;
  8266. if (v.y > max.y)
  8267. max.y = v.y;
  8268. if (v.z > max.z)
  8269. max.z = v.z;
  8270. };
  8271. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8272. for (var prop in source) {
  8273. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8274. continue;
  8275. }
  8276. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8277. continue;
  8278. }
  8279. var sourceValue = source[prop];
  8280. var typeOfSourceValue = typeof sourceValue;
  8281. if (typeOfSourceValue === "function") {
  8282. continue;
  8283. }
  8284. if (typeOfSourceValue === "object") {
  8285. if (sourceValue instanceof Array) {
  8286. destination[prop] = [];
  8287. if (sourceValue.length > 0) {
  8288. if (typeof sourceValue[0] == "object") {
  8289. for (var index = 0; index < sourceValue.length; index++) {
  8290. var clonedValue = cloneValue(sourceValue[index], destination);
  8291. if (destination[prop].indexOf(clonedValue) === -1) {
  8292. destination[prop].push(clonedValue);
  8293. }
  8294. }
  8295. }
  8296. else {
  8297. destination[prop] = sourceValue.slice(0);
  8298. }
  8299. }
  8300. }
  8301. else {
  8302. destination[prop] = cloneValue(sourceValue, destination);
  8303. }
  8304. }
  8305. else {
  8306. destination[prop] = sourceValue;
  8307. }
  8308. }
  8309. };
  8310. Tools.IsEmpty = function (obj) {
  8311. for (var i in obj) {
  8312. if (obj.hasOwnProperty(i)) {
  8313. return false;
  8314. }
  8315. }
  8316. return true;
  8317. };
  8318. Tools.RegisterTopRootEvents = function (events) {
  8319. for (var index = 0; index < events.length; index++) {
  8320. var event = events[index];
  8321. window.addEventListener(event.name, event.handler, false);
  8322. try {
  8323. if (window.parent) {
  8324. window.parent.addEventListener(event.name, event.handler, false);
  8325. }
  8326. }
  8327. catch (e) {
  8328. // Silently fails...
  8329. }
  8330. }
  8331. };
  8332. Tools.UnregisterTopRootEvents = function (events) {
  8333. for (var index = 0; index < events.length; index++) {
  8334. var event = events[index];
  8335. window.removeEventListener(event.name, event.handler);
  8336. try {
  8337. if (window.parent) {
  8338. window.parent.removeEventListener(event.name, event.handler);
  8339. }
  8340. }
  8341. catch (e) {
  8342. // Silently fails...
  8343. }
  8344. }
  8345. };
  8346. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8347. if (mimeType === void 0) { mimeType = "image/png"; }
  8348. // Read the contents of the framebuffer
  8349. var numberOfChannelsByLine = width * 4;
  8350. var halfHeight = height / 2;
  8351. //Reading datas from WebGL
  8352. var data = engine.readPixels(0, 0, width, height);
  8353. //To flip image on Y axis.
  8354. for (var i = 0; i < halfHeight; i++) {
  8355. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8356. var currentCell = j + i * numberOfChannelsByLine;
  8357. var targetLine = height - i - 1;
  8358. var targetCell = j + targetLine * numberOfChannelsByLine;
  8359. var temp = data[currentCell];
  8360. data[currentCell] = data[targetCell];
  8361. data[targetCell] = temp;
  8362. }
  8363. }
  8364. // Create a 2D canvas to store the result
  8365. if (!screenshotCanvas) {
  8366. screenshotCanvas = document.createElement('canvas');
  8367. }
  8368. screenshotCanvas.width = width;
  8369. screenshotCanvas.height = height;
  8370. var context = screenshotCanvas.getContext('2d');
  8371. if (context) {
  8372. // Copy the pixels to a 2D canvas
  8373. var imageData = context.createImageData(width, height);
  8374. var castData = (imageData.data);
  8375. castData.set(data);
  8376. context.putImageData(imageData, 0, 0);
  8377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8378. }
  8379. };
  8380. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8381. if (mimeType === void 0) { mimeType = "image/png"; }
  8382. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8383. if (successCallback) {
  8384. successCallback(base64Image);
  8385. }
  8386. else {
  8387. // We need HTMLCanvasElement.toBlob for HD screenshots
  8388. if (!screenshotCanvas.toBlob) {
  8389. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8390. screenshotCanvas.toBlob = function (callback, type, quality) {
  8391. var _this = this;
  8392. setTimeout(function () {
  8393. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8394. for (var i = 0; i < len; i++) {
  8395. arr[i] = binStr.charCodeAt(i);
  8396. }
  8397. callback(new Blob([arr], { type: type || 'image/png' }));
  8398. });
  8399. };
  8400. }
  8401. screenshotCanvas.toBlob(function (blob) {
  8402. var url = URL.createObjectURL(blob);
  8403. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8404. if (("download" in document.createElement("a"))) {
  8405. var a = window.document.createElement("a");
  8406. a.href = url;
  8407. if (fileName) {
  8408. a.setAttribute("download", fileName);
  8409. }
  8410. else {
  8411. var date = new Date();
  8412. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8413. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8414. }
  8415. window.document.body.appendChild(a);
  8416. a.addEventListener("click", function () {
  8417. if (a.parentElement) {
  8418. a.parentElement.removeChild(a);
  8419. }
  8420. });
  8421. a.click();
  8422. }
  8423. else {
  8424. var newWindow = window.open("");
  8425. if (!newWindow)
  8426. return;
  8427. var img = newWindow.document.createElement("img");
  8428. img.onload = function () {
  8429. // no longer need to read the blob so it's revoked
  8430. URL.revokeObjectURL(url);
  8431. };
  8432. img.src = url;
  8433. newWindow.document.body.appendChild(img);
  8434. }
  8435. });
  8436. }
  8437. };
  8438. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8439. if (mimeType === void 0) { mimeType = "image/png"; }
  8440. var width;
  8441. var height;
  8442. // If a precision value is specified
  8443. if (size.precision) {
  8444. width = Math.round(engine.getRenderWidth() * size.precision);
  8445. height = Math.round(width / engine.getAspectRatio(camera));
  8446. }
  8447. else if (size.width && size.height) {
  8448. width = size.width;
  8449. height = size.height;
  8450. }
  8451. else if (size.width && !size.height) {
  8452. width = size.width;
  8453. height = Math.round(width / engine.getAspectRatio(camera));
  8454. }
  8455. else if (size.height && !size.width) {
  8456. height = size.height;
  8457. width = Math.round(height * engine.getAspectRatio(camera));
  8458. }
  8459. else if (!isNaN(size)) {
  8460. height = size;
  8461. width = size;
  8462. }
  8463. else {
  8464. Tools.Error("Invalid 'size' parameter !");
  8465. return;
  8466. }
  8467. if (!screenshotCanvas) {
  8468. screenshotCanvas = document.createElement('canvas');
  8469. }
  8470. screenshotCanvas.width = width;
  8471. screenshotCanvas.height = height;
  8472. var renderContext = screenshotCanvas.getContext("2d");
  8473. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8474. var newWidth = width;
  8475. var newHeight = newWidth / ratio;
  8476. if (newHeight > height) {
  8477. newHeight = height;
  8478. newWidth = newHeight * ratio;
  8479. }
  8480. var offsetX = Math.max(0, width - newWidth) / 2;
  8481. var offsetY = Math.max(0, height - newHeight) / 2;
  8482. var renderingCanvas = engine.getRenderingCanvas();
  8483. if (renderContext && renderingCanvas) {
  8484. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8485. }
  8486. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8487. };
  8488. /**
  8489. * Generates an image screenshot from the specified camera.
  8490. *
  8491. * @param engine The engine to use for rendering
  8492. * @param camera The camera to use for rendering
  8493. * @param size This parameter can be set to a single number or to an object with the
  8494. * following (optional) properties: precision, width, height. If a single number is passed,
  8495. * it will be used for both width and height. If an object is passed, the screenshot size
  8496. * will be derived from the parameters. The precision property is a multiplier allowing
  8497. * rendering at a higher or lower resolution.
  8498. * @param successCallback The callback receives a single parameter which contains the
  8499. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8500. * src parameter of an <img> to display it.
  8501. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8502. * Check your browser for supported MIME types.
  8503. * @param samples Texture samples (default: 1)
  8504. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8505. * @param fileName A name for for the downloaded file.
  8506. * @constructor
  8507. */
  8508. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8509. if (mimeType === void 0) { mimeType = "image/png"; }
  8510. if (samples === void 0) { samples = 1; }
  8511. if (antialiasing === void 0) { antialiasing = false; }
  8512. var width;
  8513. var height;
  8514. //If a precision value is specified
  8515. if (size.precision) {
  8516. width = Math.round(engine.getRenderWidth() * size.precision);
  8517. height = Math.round(width / engine.getAspectRatio(camera));
  8518. size = { width: width, height: height };
  8519. }
  8520. else if (size.width && size.height) {
  8521. width = size.width;
  8522. height = size.height;
  8523. }
  8524. else if (size.width && !size.height) {
  8525. width = size.width;
  8526. height = Math.round(width / engine.getAspectRatio(camera));
  8527. size = { width: width, height: height };
  8528. }
  8529. else if (size.height && !size.width) {
  8530. height = size.height;
  8531. width = Math.round(height * engine.getAspectRatio(camera));
  8532. size = { width: width, height: height };
  8533. }
  8534. else if (!isNaN(size)) {
  8535. height = size;
  8536. width = size;
  8537. }
  8538. else {
  8539. Tools.Error("Invalid 'size' parameter !");
  8540. return;
  8541. }
  8542. var scene = camera.getScene();
  8543. var previousCamera = null;
  8544. if (scene.activeCamera !== camera) {
  8545. previousCamera = scene.activeCamera;
  8546. scene.activeCamera = camera;
  8547. }
  8548. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8549. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8550. texture.renderList = null;
  8551. texture.samples = samples;
  8552. if (antialiasing) {
  8553. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8554. }
  8555. texture.onAfterRenderObservable.add(function () {
  8556. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8557. });
  8558. scene.incrementRenderId();
  8559. scene.resetCachedMaterial();
  8560. texture.render(true);
  8561. texture.dispose();
  8562. if (previousCamera) {
  8563. scene.activeCamera = previousCamera;
  8564. }
  8565. camera.getProjectionMatrix(true); // Force cache refresh;
  8566. };
  8567. // XHR response validator for local file scenario
  8568. Tools.ValidateXHRData = function (xhr, dataType) {
  8569. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8570. if (dataType === void 0) { dataType = 7; }
  8571. try {
  8572. if (dataType & 1) {
  8573. if (xhr.responseText && xhr.responseText.length > 0) {
  8574. return true;
  8575. }
  8576. else if (dataType === 1) {
  8577. return false;
  8578. }
  8579. }
  8580. if (dataType & 2) {
  8581. // Check header width and height since there is no "TGA" magic number
  8582. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8583. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8584. return true;
  8585. }
  8586. else if (dataType === 2) {
  8587. return false;
  8588. }
  8589. }
  8590. if (dataType & 4) {
  8591. // Check for the "DDS" magic number
  8592. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8593. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8594. return true;
  8595. }
  8596. else {
  8597. return false;
  8598. }
  8599. }
  8600. }
  8601. catch (e) {
  8602. // Global protection
  8603. }
  8604. return false;
  8605. };
  8606. /**
  8607. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8608. * Be aware Math.random() could cause collisions, but:
  8609. * "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"
  8610. */
  8611. Tools.RandomId = function () {
  8612. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8613. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8614. return v.toString(16);
  8615. });
  8616. };
  8617. /**
  8618. * Test if the given uri is a base64 string.
  8619. * @param uri The uri to test
  8620. * @return True if the uri is a base64 string or false otherwise.
  8621. */
  8622. Tools.IsBase64 = function (uri) {
  8623. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8624. };
  8625. /**
  8626. * Decode the given base64 uri.
  8627. * @param uri The uri to decode
  8628. * @return The decoded base64 data.
  8629. */
  8630. Tools.DecodeBase64 = function (uri) {
  8631. var decodedString = atob(uri.split(",")[1]);
  8632. var bufferLength = decodedString.length;
  8633. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8634. for (var i = 0; i < bufferLength; i++) {
  8635. bufferView[i] = decodedString.charCodeAt(i);
  8636. }
  8637. return bufferView.buffer;
  8638. };
  8639. Object.defineProperty(Tools, "NoneLogLevel", {
  8640. get: function () {
  8641. return Tools._NoneLogLevel;
  8642. },
  8643. enumerable: true,
  8644. configurable: true
  8645. });
  8646. Object.defineProperty(Tools, "MessageLogLevel", {
  8647. get: function () {
  8648. return Tools._MessageLogLevel;
  8649. },
  8650. enumerable: true,
  8651. configurable: true
  8652. });
  8653. Object.defineProperty(Tools, "WarningLogLevel", {
  8654. get: function () {
  8655. return Tools._WarningLogLevel;
  8656. },
  8657. enumerable: true,
  8658. configurable: true
  8659. });
  8660. Object.defineProperty(Tools, "ErrorLogLevel", {
  8661. get: function () {
  8662. return Tools._ErrorLogLevel;
  8663. },
  8664. enumerable: true,
  8665. configurable: true
  8666. });
  8667. Object.defineProperty(Tools, "AllLogLevel", {
  8668. get: function () {
  8669. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Tools._AddLogEntry = function (entry) {
  8675. Tools._LogCache = entry + Tools._LogCache;
  8676. if (Tools.OnNewCacheEntry) {
  8677. Tools.OnNewCacheEntry(entry);
  8678. }
  8679. };
  8680. Tools._FormatMessage = function (message) {
  8681. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8682. var date = new Date();
  8683. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8684. };
  8685. Tools._LogDisabled = function (message) {
  8686. // nothing to do
  8687. };
  8688. Tools._LogEnabled = function (message) {
  8689. var formattedMessage = Tools._FormatMessage(message);
  8690. console.log("BJS - " + formattedMessage);
  8691. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8692. Tools._AddLogEntry(entry);
  8693. };
  8694. Tools._WarnDisabled = function (message) {
  8695. // nothing to do
  8696. };
  8697. Tools._WarnEnabled = function (message) {
  8698. var formattedMessage = Tools._FormatMessage(message);
  8699. console.warn("BJS - " + formattedMessage);
  8700. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8701. Tools._AddLogEntry(entry);
  8702. };
  8703. Tools._ErrorDisabled = function (message) {
  8704. // nothing to do
  8705. };
  8706. Tools._ErrorEnabled = function (message) {
  8707. Tools.errorsCount++;
  8708. var formattedMessage = Tools._FormatMessage(message);
  8709. console.error("BJS - " + formattedMessage);
  8710. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8711. Tools._AddLogEntry(entry);
  8712. };
  8713. Object.defineProperty(Tools, "LogCache", {
  8714. get: function () {
  8715. return Tools._LogCache;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Tools.ClearLogCache = function () {
  8721. Tools._LogCache = "";
  8722. Tools.errorsCount = 0;
  8723. };
  8724. Object.defineProperty(Tools, "LogLevels", {
  8725. set: function (level) {
  8726. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8727. Tools.Log = Tools._LogEnabled;
  8728. }
  8729. else {
  8730. Tools.Log = Tools._LogDisabled;
  8731. }
  8732. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8733. Tools.Warn = Tools._WarnEnabled;
  8734. }
  8735. else {
  8736. Tools.Warn = Tools._WarnDisabled;
  8737. }
  8738. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8739. Tools.Error = Tools._ErrorEnabled;
  8740. }
  8741. else {
  8742. Tools.Error = Tools._ErrorDisabled;
  8743. }
  8744. },
  8745. enumerable: true,
  8746. configurable: true
  8747. });
  8748. Tools.IsWindowObjectExist = function () {
  8749. return (typeof window) !== "undefined";
  8750. };
  8751. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8752. get: function () {
  8753. return Tools._PerformanceNoneLogLevel;
  8754. },
  8755. enumerable: true,
  8756. configurable: true
  8757. });
  8758. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8759. get: function () {
  8760. return Tools._PerformanceUserMarkLogLevel;
  8761. },
  8762. enumerable: true,
  8763. configurable: true
  8764. });
  8765. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8766. get: function () {
  8767. return Tools._PerformanceConsoleLogLevel;
  8768. },
  8769. enumerable: true,
  8770. configurable: true
  8771. });
  8772. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8773. set: function (level) {
  8774. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8775. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8776. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8777. return;
  8778. }
  8779. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8780. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8781. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8782. return;
  8783. }
  8784. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8785. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8791. };
  8792. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8793. };
  8794. Tools._StartUserMark = function (counterName, condition) {
  8795. if (condition === void 0) { condition = true; }
  8796. if (!Tools._performance) {
  8797. if (!Tools.IsWindowObjectExist()) {
  8798. return;
  8799. }
  8800. Tools._performance = window.performance;
  8801. }
  8802. if (!condition || !Tools._performance.mark) {
  8803. return;
  8804. }
  8805. Tools._performance.mark(counterName + "-Begin");
  8806. };
  8807. Tools._EndUserMark = function (counterName, condition) {
  8808. if (condition === void 0) { condition = true; }
  8809. if (!condition || !Tools._performance.mark) {
  8810. return;
  8811. }
  8812. Tools._performance.mark(counterName + "-End");
  8813. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8814. };
  8815. Tools._StartPerformanceConsole = function (counterName, condition) {
  8816. if (condition === void 0) { condition = true; }
  8817. if (!condition) {
  8818. return;
  8819. }
  8820. Tools._StartUserMark(counterName, condition);
  8821. if (console.time) {
  8822. console.time(counterName);
  8823. }
  8824. };
  8825. Tools._EndPerformanceConsole = function (counterName, condition) {
  8826. if (condition === void 0) { condition = true; }
  8827. if (!condition) {
  8828. return;
  8829. }
  8830. Tools._EndUserMark(counterName, condition);
  8831. if (console.time) {
  8832. console.timeEnd(counterName);
  8833. }
  8834. };
  8835. Object.defineProperty(Tools, "Now", {
  8836. get: function () {
  8837. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8838. return window.performance.now();
  8839. }
  8840. return new Date().getTime();
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. /**
  8846. * This method will return the name of the class used to create the instance of the given object.
  8847. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8848. * @param object the object to get the class name from
  8849. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8850. */
  8851. Tools.GetClassName = function (object, isType) {
  8852. if (isType === void 0) { isType = false; }
  8853. var name = null;
  8854. if (!isType && object.getClassName) {
  8855. name = object.getClassName();
  8856. }
  8857. else {
  8858. if (object instanceof Object) {
  8859. var classObj = isType ? object : Object.getPrototypeOf(object);
  8860. name = classObj.constructor["__bjsclassName__"];
  8861. }
  8862. if (!name) {
  8863. name = typeof object;
  8864. }
  8865. }
  8866. return name;
  8867. };
  8868. Tools.First = function (array, predicate) {
  8869. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8870. var el = array_1[_i];
  8871. if (predicate(el)) {
  8872. return el;
  8873. }
  8874. }
  8875. return null;
  8876. };
  8877. /**
  8878. * This method will return the name of the full name of the class, including its owning module (if any).
  8879. * 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).
  8880. * @param object the object to get the class name from
  8881. * @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.
  8882. */
  8883. Tools.getFullClassName = function (object, isType) {
  8884. if (isType === void 0) { isType = false; }
  8885. var className = null;
  8886. var moduleName = null;
  8887. if (!isType && object.getClassName) {
  8888. className = object.getClassName();
  8889. }
  8890. else {
  8891. if (object instanceof Object) {
  8892. var classObj = isType ? object : Object.getPrototypeOf(object);
  8893. className = classObj.constructor["__bjsclassName__"];
  8894. moduleName = classObj.constructor["__bjsmoduleName__"];
  8895. }
  8896. if (!className) {
  8897. className = typeof object;
  8898. }
  8899. }
  8900. if (!className) {
  8901. return null;
  8902. }
  8903. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8904. };
  8905. /**
  8906. * 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.
  8907. * @param array
  8908. */
  8909. Tools.arrayOrStringFeeder = function (array) {
  8910. return function (index) {
  8911. if (index >= array.length) {
  8912. return null;
  8913. }
  8914. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8915. if (val && val.getHashCode) {
  8916. val = val.getHashCode();
  8917. }
  8918. if (typeof val === "string") {
  8919. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8920. }
  8921. return val;
  8922. };
  8923. };
  8924. /**
  8925. * Compute the hashCode of a stream of number
  8926. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8927. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8928. * @return the hash code computed
  8929. */
  8930. Tools.hashCodeFromStream = function (feeder) {
  8931. // Based from here: http://stackoverflow.com/a/7616484/802124
  8932. var hash = 0;
  8933. var index = 0;
  8934. var chr = feeder(index++);
  8935. while (chr != null) {
  8936. hash = ((hash << 5) - hash) + chr;
  8937. hash |= 0; // Convert to 32bit integer
  8938. chr = feeder(index++);
  8939. }
  8940. return hash;
  8941. };
  8942. /**
  8943. * Returns a promise that resolves after the given amount of time.
  8944. * @param delay Number of milliseconds to delay
  8945. * @returns Promise that resolves after the given amount of time
  8946. */
  8947. Tools.DelayAsync = function (delay) {
  8948. return new Promise(function (resolve) {
  8949. setTimeout(function () {
  8950. resolve();
  8951. }, delay);
  8952. });
  8953. };
  8954. Tools.BaseUrl = "";
  8955. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8956. /**
  8957. * Default behaviour for cors in the application.
  8958. * It can be a string if the expected behavior is identical in the entire app.
  8959. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8960. */
  8961. Tools.CorsBehavior = "anonymous";
  8962. Tools.UseFallbackTexture = true;
  8963. /**
  8964. * Use this object to register external classes like custom textures or material
  8965. * to allow the laoders to instantiate them
  8966. */
  8967. Tools.RegisteredExternalClasses = {};
  8968. // Used in case of a texture loading problem
  8969. 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";
  8970. Tools.PreprocessUrl = function (url) {
  8971. return url;
  8972. };
  8973. // Logs
  8974. Tools._NoneLogLevel = 0;
  8975. Tools._MessageLogLevel = 1;
  8976. Tools._WarningLogLevel = 2;
  8977. Tools._ErrorLogLevel = 4;
  8978. Tools._LogCache = "";
  8979. Tools.errorsCount = 0;
  8980. Tools.Log = Tools._LogEnabled;
  8981. Tools.Warn = Tools._WarnEnabled;
  8982. Tools.Error = Tools._ErrorEnabled;
  8983. // Performances
  8984. Tools._PerformanceNoneLogLevel = 0;
  8985. Tools._PerformanceUserMarkLogLevel = 1;
  8986. Tools._PerformanceConsoleLogLevel = 2;
  8987. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8988. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8989. return Tools;
  8990. }());
  8991. BABYLON.Tools = Tools;
  8992. /**
  8993. * This class is used to track a performance counter which is number based.
  8994. * The user has access to many properties which give statistics of different nature
  8995. *
  8996. * The implementer can track two kinds of Performance Counter: time and count
  8997. * 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.
  8998. * 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.
  8999. */
  9000. var PerfCounter = /** @class */ (function () {
  9001. function PerfCounter() {
  9002. this._startMonitoringTime = 0;
  9003. this._min = 0;
  9004. this._max = 0;
  9005. this._average = 0;
  9006. this._lastSecAverage = 0;
  9007. this._current = 0;
  9008. this._totalValueCount = 0;
  9009. this._totalAccumulated = 0;
  9010. this._lastSecAccumulated = 0;
  9011. this._lastSecTime = 0;
  9012. this._lastSecValueCount = 0;
  9013. }
  9014. Object.defineProperty(PerfCounter.prototype, "min", {
  9015. /**
  9016. * Returns the smallest value ever
  9017. */
  9018. get: function () {
  9019. return this._min;
  9020. },
  9021. enumerable: true,
  9022. configurable: true
  9023. });
  9024. Object.defineProperty(PerfCounter.prototype, "max", {
  9025. /**
  9026. * Returns the biggest value ever
  9027. */
  9028. get: function () {
  9029. return this._max;
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(PerfCounter.prototype, "average", {
  9035. /**
  9036. * Returns the average value since the performance counter is running
  9037. */
  9038. get: function () {
  9039. return this._average;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9045. /**
  9046. * Returns the average value of the last second the counter was monitored
  9047. */
  9048. get: function () {
  9049. return this._lastSecAverage;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(PerfCounter.prototype, "current", {
  9055. /**
  9056. * Returns the current value
  9057. */
  9058. get: function () {
  9059. return this._current;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(PerfCounter.prototype, "total", {
  9065. get: function () {
  9066. return this._totalAccumulated;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(PerfCounter.prototype, "count", {
  9072. get: function () {
  9073. return this._totalValueCount;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. /**
  9079. * Call this method to start monitoring a new frame.
  9080. * 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.
  9081. */
  9082. PerfCounter.prototype.fetchNewFrame = function () {
  9083. this._totalValueCount++;
  9084. this._current = 0;
  9085. this._lastSecValueCount++;
  9086. };
  9087. /**
  9088. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9089. * @param newCount the count value to add to the monitored count
  9090. * @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.
  9091. */
  9092. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9093. if (!PerfCounter.Enabled) {
  9094. return;
  9095. }
  9096. this._current += newCount;
  9097. if (fetchResult) {
  9098. this._fetchResult();
  9099. }
  9100. };
  9101. /**
  9102. * Start monitoring this performance counter
  9103. */
  9104. PerfCounter.prototype.beginMonitoring = function () {
  9105. if (!PerfCounter.Enabled) {
  9106. return;
  9107. }
  9108. this._startMonitoringTime = Tools.Now;
  9109. };
  9110. /**
  9111. * Compute the time lapsed since the previous beginMonitoring() call.
  9112. * @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
  9113. */
  9114. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9115. if (newFrame === void 0) { newFrame = true; }
  9116. if (!PerfCounter.Enabled) {
  9117. return;
  9118. }
  9119. if (newFrame) {
  9120. this.fetchNewFrame();
  9121. }
  9122. var currentTime = Tools.Now;
  9123. this._current = currentTime - this._startMonitoringTime;
  9124. if (newFrame) {
  9125. this._fetchResult();
  9126. }
  9127. };
  9128. PerfCounter.prototype._fetchResult = function () {
  9129. this._totalAccumulated += this._current;
  9130. this._lastSecAccumulated += this._current;
  9131. // Min/Max update
  9132. this._min = Math.min(this._min, this._current);
  9133. this._max = Math.max(this._max, this._current);
  9134. this._average = this._totalAccumulated / this._totalValueCount;
  9135. // Reset last sec?
  9136. var now = Tools.Now;
  9137. if ((now - this._lastSecTime) > 1000) {
  9138. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9139. this._lastSecTime = now;
  9140. this._lastSecAccumulated = 0;
  9141. this._lastSecValueCount = 0;
  9142. }
  9143. };
  9144. PerfCounter.Enabled = true;
  9145. return PerfCounter;
  9146. }());
  9147. BABYLON.PerfCounter = PerfCounter;
  9148. /**
  9149. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9150. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9151. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9152. * @param name The name of the class, case should be preserved
  9153. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9154. */
  9155. function className(name, module) {
  9156. return function (target) {
  9157. target["__bjsclassName__"] = name;
  9158. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9159. };
  9160. }
  9161. BABYLON.className = className;
  9162. /**
  9163. * An implementation of a loop for asynchronous functions.
  9164. */
  9165. var AsyncLoop = /** @class */ (function () {
  9166. /**
  9167. * Constroctor.
  9168. * @param iterations the number of iterations.
  9169. * @param _fn the function to run each iteration
  9170. * @param _successCallback the callback that will be called upon succesful execution
  9171. * @param offset starting offset.
  9172. */
  9173. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9174. if (offset === void 0) { offset = 0; }
  9175. this.iterations = iterations;
  9176. this._fn = _fn;
  9177. this._successCallback = _successCallback;
  9178. this.index = offset - 1;
  9179. this._done = false;
  9180. }
  9181. /**
  9182. * Execute the next iteration. Must be called after the last iteration was finished.
  9183. */
  9184. AsyncLoop.prototype.executeNext = function () {
  9185. if (!this._done) {
  9186. if (this.index + 1 < this.iterations) {
  9187. ++this.index;
  9188. this._fn(this);
  9189. }
  9190. else {
  9191. this.breakLoop();
  9192. }
  9193. }
  9194. };
  9195. /**
  9196. * Break the loop and run the success callback.
  9197. */
  9198. AsyncLoop.prototype.breakLoop = function () {
  9199. this._done = true;
  9200. this._successCallback();
  9201. };
  9202. /**
  9203. * Helper function
  9204. */
  9205. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9206. if (offset === void 0) { offset = 0; }
  9207. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9208. loop.executeNext();
  9209. return loop;
  9210. };
  9211. /**
  9212. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9213. * @param iterations total number of iterations
  9214. * @param syncedIterations number of synchronous iterations in each async iteration.
  9215. * @param fn the function to call each iteration.
  9216. * @param callback a success call back that will be called when iterating stops.
  9217. * @param breakFunction a break condition (optional)
  9218. * @param timeout timeout settings for the setTimeout function. default - 0.
  9219. * @constructor
  9220. */
  9221. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9222. if (timeout === void 0) { timeout = 0; }
  9223. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9224. if (breakFunction && breakFunction())
  9225. loop.breakLoop();
  9226. else {
  9227. setTimeout(function () {
  9228. for (var i = 0; i < syncedIterations; ++i) {
  9229. var iteration = (loop.index * syncedIterations) + i;
  9230. if (iteration >= iterations)
  9231. break;
  9232. fn(iteration);
  9233. if (breakFunction && breakFunction()) {
  9234. loop.breakLoop();
  9235. break;
  9236. }
  9237. }
  9238. loop.executeNext();
  9239. }, timeout);
  9240. }
  9241. }, callback);
  9242. };
  9243. return AsyncLoop;
  9244. }());
  9245. BABYLON.AsyncLoop = AsyncLoop;
  9246. })(BABYLON || (BABYLON = {}));
  9247. //# sourceMappingURL=babylon.tools.js.map
  9248. var BABYLON;
  9249. (function (BABYLON) {
  9250. var PromiseStates;
  9251. (function (PromiseStates) {
  9252. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9253. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9254. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9255. })(PromiseStates || (PromiseStates = {}));
  9256. var FulFillmentAgregator = /** @class */ (function () {
  9257. function FulFillmentAgregator() {
  9258. this.count = 0;
  9259. this.target = 0;
  9260. this.results = [];
  9261. }
  9262. return FulFillmentAgregator;
  9263. }());
  9264. var InternalPromise = /** @class */ (function () {
  9265. function InternalPromise(resolver) {
  9266. var _this = this;
  9267. this._state = PromiseStates.Pending;
  9268. this._children = new Array();
  9269. this._rejectWasConsumed = false;
  9270. if (!resolver) {
  9271. return;
  9272. }
  9273. try {
  9274. resolver(function (value) {
  9275. _this._resolve(value);
  9276. }, function (reason) {
  9277. _this._reject(reason);
  9278. });
  9279. }
  9280. catch (e) {
  9281. this._reject(e);
  9282. }
  9283. }
  9284. InternalPromise.prototype.catch = function (onRejected) {
  9285. return this.then(undefined, onRejected);
  9286. };
  9287. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9288. var _this = this;
  9289. var newPromise = new InternalPromise();
  9290. newPromise._onFulfilled = onFulfilled;
  9291. newPromise._onRejected = onRejected;
  9292. // Composition
  9293. this._children.push(newPromise);
  9294. if (this._state !== PromiseStates.Pending) {
  9295. BABYLON.Tools.SetImmediate(function () {
  9296. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9297. var returnedValue = newPromise._resolve(_this._result);
  9298. if (returnedValue !== undefined && returnedValue !== null) {
  9299. if (returnedValue._state !== undefined) {
  9300. var returnedPromise = returnedValue;
  9301. newPromise._children.push(returnedPromise);
  9302. newPromise = returnedPromise;
  9303. }
  9304. else {
  9305. newPromise._result = returnedValue;
  9306. }
  9307. }
  9308. }
  9309. else {
  9310. newPromise._reject(_this._reason);
  9311. }
  9312. });
  9313. }
  9314. return newPromise;
  9315. };
  9316. InternalPromise.prototype._moveChildren = function (children) {
  9317. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9318. if (this._state === PromiseStates.Fulfilled) {
  9319. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9320. var child = _b[_i];
  9321. child._resolve(this._result);
  9322. }
  9323. }
  9324. else if (this._state === PromiseStates.Rejected) {
  9325. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9326. var child = _d[_c];
  9327. child._reject(this._reason);
  9328. }
  9329. }
  9330. var _a;
  9331. };
  9332. InternalPromise.prototype._resolve = function (value) {
  9333. try {
  9334. this._state = PromiseStates.Fulfilled;
  9335. this._result = value;
  9336. var returnedValue = null;
  9337. if (this._onFulfilled) {
  9338. returnedValue = this._onFulfilled(value);
  9339. }
  9340. if (returnedValue !== undefined && returnedValue !== null) {
  9341. if (returnedValue._state !== undefined) {
  9342. // Transmit children
  9343. var returnedPromise = returnedValue;
  9344. returnedPromise._moveChildren(this._children);
  9345. }
  9346. else {
  9347. value = returnedValue;
  9348. }
  9349. }
  9350. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9351. var child = _a[_i];
  9352. child._resolve(value);
  9353. }
  9354. this._children.length = 0;
  9355. delete this._onFulfilled;
  9356. delete this._onRejected;
  9357. return returnedValue;
  9358. }
  9359. catch (e) {
  9360. this._reject(e);
  9361. }
  9362. return null;
  9363. };
  9364. InternalPromise.prototype._reject = function (reason) {
  9365. this._state = PromiseStates.Rejected;
  9366. this._reason = reason;
  9367. if (this._onRejected) {
  9368. try {
  9369. this._onRejected(reason);
  9370. this._rejectWasConsumed = true;
  9371. }
  9372. catch (e) {
  9373. reason = e;
  9374. }
  9375. }
  9376. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9377. var child = _a[_i];
  9378. if (this._rejectWasConsumed) {
  9379. child._resolve(null);
  9380. }
  9381. else {
  9382. child._reject(reason);
  9383. }
  9384. }
  9385. this._children.length = 0;
  9386. delete this._onFulfilled;
  9387. delete this._onRejected;
  9388. };
  9389. InternalPromise.resolve = function (value) {
  9390. var newPromise = new InternalPromise();
  9391. newPromise._resolve(value);
  9392. return newPromise;
  9393. };
  9394. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9395. promise.then(function (value) {
  9396. agregator.results[index] = value;
  9397. agregator.count++;
  9398. if (agregator.count === agregator.target) {
  9399. agregator.rootPromise._resolve(agregator.results);
  9400. }
  9401. return null;
  9402. }, function (reason) {
  9403. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9404. agregator.rootPromise._reject(reason);
  9405. }
  9406. });
  9407. };
  9408. InternalPromise.all = function (promises) {
  9409. var newPromise = new InternalPromise();
  9410. var agregator = new FulFillmentAgregator();
  9411. agregator.target = promises.length;
  9412. agregator.rootPromise = newPromise;
  9413. if (promises.length) {
  9414. for (var index = 0; index < promises.length; index++) {
  9415. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9416. }
  9417. }
  9418. else {
  9419. newPromise._resolve([]);
  9420. }
  9421. return newPromise;
  9422. };
  9423. return InternalPromise;
  9424. }());
  9425. /**
  9426. * Helper class that provides a small promise polyfill
  9427. */
  9428. var PromisePolyfill = /** @class */ (function () {
  9429. function PromisePolyfill() {
  9430. }
  9431. /**
  9432. * Static function used to check if the polyfill is required
  9433. * If this is the case then the function will inject the polyfill to window.Promise
  9434. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9435. */
  9436. PromisePolyfill.Apply = function (force) {
  9437. if (force === void 0) { force = false; }
  9438. if (force || typeof Promise === 'undefined') {
  9439. var root = window;
  9440. root.Promise = InternalPromise;
  9441. }
  9442. };
  9443. return PromisePolyfill;
  9444. }());
  9445. BABYLON.PromisePolyfill = PromisePolyfill;
  9446. })(BABYLON || (BABYLON = {}));
  9447. //# sourceMappingURL=babylon.promise.js.map
  9448. var BABYLON;
  9449. (function (BABYLON) {
  9450. var _AlphaState = /** @class */ (function () {
  9451. /**
  9452. * Initializes the state.
  9453. */
  9454. function _AlphaState() {
  9455. this._isAlphaBlendDirty = false;
  9456. this._isBlendFunctionParametersDirty = false;
  9457. this._isBlendEquationParametersDirty = false;
  9458. this._isBlendConstantsDirty = false;
  9459. this._alphaBlend = false;
  9460. this._blendFunctionParameters = new Array(4);
  9461. this._blendEquationParameters = new Array(2);
  9462. this._blendConstants = new Array(4);
  9463. this.reset();
  9464. }
  9465. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9466. get: function () {
  9467. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9468. },
  9469. enumerable: true,
  9470. configurable: true
  9471. });
  9472. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9473. get: function () {
  9474. return this._alphaBlend;
  9475. },
  9476. set: function (value) {
  9477. if (this._alphaBlend === value) {
  9478. return;
  9479. }
  9480. this._alphaBlend = value;
  9481. this._isAlphaBlendDirty = true;
  9482. },
  9483. enumerable: true,
  9484. configurable: true
  9485. });
  9486. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9487. if (this._blendConstants[0] === r &&
  9488. this._blendConstants[1] === g &&
  9489. this._blendConstants[2] === b &&
  9490. this._blendConstants[3] === a) {
  9491. return;
  9492. }
  9493. this._blendConstants[0] = r;
  9494. this._blendConstants[1] = g;
  9495. this._blendConstants[2] = b;
  9496. this._blendConstants[3] = a;
  9497. this._isBlendConstantsDirty = true;
  9498. };
  9499. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9500. if (this._blendFunctionParameters[0] === value0 &&
  9501. this._blendFunctionParameters[1] === value1 &&
  9502. this._blendFunctionParameters[2] === value2 &&
  9503. this._blendFunctionParameters[3] === value3) {
  9504. return;
  9505. }
  9506. this._blendFunctionParameters[0] = value0;
  9507. this._blendFunctionParameters[1] = value1;
  9508. this._blendFunctionParameters[2] = value2;
  9509. this._blendFunctionParameters[3] = value3;
  9510. this._isBlendFunctionParametersDirty = true;
  9511. };
  9512. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9513. if (this._blendEquationParameters[0] === rgb &&
  9514. this._blendEquationParameters[1] === alpha) {
  9515. return;
  9516. }
  9517. this._blendEquationParameters[0] = rgb;
  9518. this._blendEquationParameters[1] = alpha;
  9519. this._isBlendEquationParametersDirty = true;
  9520. };
  9521. _AlphaState.prototype.reset = function () {
  9522. this._alphaBlend = false;
  9523. this._blendFunctionParameters[0] = null;
  9524. this._blendFunctionParameters[1] = null;
  9525. this._blendFunctionParameters[2] = null;
  9526. this._blendFunctionParameters[3] = null;
  9527. this._blendEquationParameters[0] = null;
  9528. this._blendEquationParameters[1] = null;
  9529. this._blendConstants[0] = null;
  9530. this._blendConstants[1] = null;
  9531. this._blendConstants[2] = null;
  9532. this._blendConstants[3] = null;
  9533. this._isAlphaBlendDirty = true;
  9534. this._isBlendFunctionParametersDirty = false;
  9535. this._isBlendEquationParametersDirty = false;
  9536. this._isBlendConstantsDirty = false;
  9537. };
  9538. _AlphaState.prototype.apply = function (gl) {
  9539. if (!this.isDirty) {
  9540. return;
  9541. }
  9542. // Alpha blend
  9543. if (this._isAlphaBlendDirty) {
  9544. if (this._alphaBlend) {
  9545. gl.enable(gl.BLEND);
  9546. }
  9547. else {
  9548. gl.disable(gl.BLEND);
  9549. }
  9550. this._isAlphaBlendDirty = false;
  9551. }
  9552. // Alpha function
  9553. if (this._isBlendFunctionParametersDirty) {
  9554. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9555. this._isBlendFunctionParametersDirty = false;
  9556. }
  9557. // Alpha equation
  9558. if (this._isBlendEquationParametersDirty) {
  9559. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9560. this._isBlendEquationParametersDirty = false;
  9561. }
  9562. // Constants
  9563. if (this._isBlendConstantsDirty) {
  9564. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9565. this._isBlendConstantsDirty = false;
  9566. }
  9567. };
  9568. return _AlphaState;
  9569. }());
  9570. BABYLON._AlphaState = _AlphaState;
  9571. })(BABYLON || (BABYLON = {}));
  9572. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9573. var BABYLON;
  9574. (function (BABYLON) {
  9575. var _DepthCullingState = /** @class */ (function () {
  9576. /**
  9577. * Initializes the state.
  9578. */
  9579. function _DepthCullingState() {
  9580. this._isDepthTestDirty = false;
  9581. this._isDepthMaskDirty = false;
  9582. this._isDepthFuncDirty = false;
  9583. this._isCullFaceDirty = false;
  9584. this._isCullDirty = false;
  9585. this._isZOffsetDirty = false;
  9586. this._isFrontFaceDirty = false;
  9587. this.reset();
  9588. }
  9589. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9590. get: function () {
  9591. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9597. get: function () {
  9598. return this._zOffset;
  9599. },
  9600. set: function (value) {
  9601. if (this._zOffset === value) {
  9602. return;
  9603. }
  9604. this._zOffset = value;
  9605. this._isZOffsetDirty = true;
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9611. get: function () {
  9612. return this._cullFace;
  9613. },
  9614. set: function (value) {
  9615. if (this._cullFace === value) {
  9616. return;
  9617. }
  9618. this._cullFace = value;
  9619. this._isCullFaceDirty = true;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9625. get: function () {
  9626. return this._cull;
  9627. },
  9628. set: function (value) {
  9629. if (this._cull === value) {
  9630. return;
  9631. }
  9632. this._cull = value;
  9633. this._isCullDirty = true;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9639. get: function () {
  9640. return this._depthFunc;
  9641. },
  9642. set: function (value) {
  9643. if (this._depthFunc === value) {
  9644. return;
  9645. }
  9646. this._depthFunc = value;
  9647. this._isDepthFuncDirty = true;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9653. get: function () {
  9654. return this._depthMask;
  9655. },
  9656. set: function (value) {
  9657. if (this._depthMask === value) {
  9658. return;
  9659. }
  9660. this._depthMask = value;
  9661. this._isDepthMaskDirty = true;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9667. get: function () {
  9668. return this._depthTest;
  9669. },
  9670. set: function (value) {
  9671. if (this._depthTest === value) {
  9672. return;
  9673. }
  9674. this._depthTest = value;
  9675. this._isDepthTestDirty = true;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9681. get: function () {
  9682. return this._frontFace;
  9683. },
  9684. set: function (value) {
  9685. if (this._frontFace === value) {
  9686. return;
  9687. }
  9688. this._frontFace = value;
  9689. this._isFrontFaceDirty = true;
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. _DepthCullingState.prototype.reset = function () {
  9695. this._depthMask = true;
  9696. this._depthTest = true;
  9697. this._depthFunc = null;
  9698. this._cullFace = null;
  9699. this._cull = null;
  9700. this._zOffset = 0;
  9701. this._frontFace = null;
  9702. this._isDepthTestDirty = true;
  9703. this._isDepthMaskDirty = true;
  9704. this._isDepthFuncDirty = false;
  9705. this._isCullFaceDirty = false;
  9706. this._isCullDirty = false;
  9707. this._isZOffsetDirty = false;
  9708. this._isFrontFaceDirty = false;
  9709. };
  9710. _DepthCullingState.prototype.apply = function (gl) {
  9711. if (!this.isDirty) {
  9712. return;
  9713. }
  9714. // Cull
  9715. if (this._isCullDirty) {
  9716. if (this.cull) {
  9717. gl.enable(gl.CULL_FACE);
  9718. }
  9719. else {
  9720. gl.disable(gl.CULL_FACE);
  9721. }
  9722. this._isCullDirty = false;
  9723. }
  9724. // Cull face
  9725. if (this._isCullFaceDirty) {
  9726. gl.cullFace(this.cullFace);
  9727. this._isCullFaceDirty = false;
  9728. }
  9729. // Depth mask
  9730. if (this._isDepthMaskDirty) {
  9731. gl.depthMask(this.depthMask);
  9732. this._isDepthMaskDirty = false;
  9733. }
  9734. // Depth test
  9735. if (this._isDepthTestDirty) {
  9736. if (this.depthTest) {
  9737. gl.enable(gl.DEPTH_TEST);
  9738. }
  9739. else {
  9740. gl.disable(gl.DEPTH_TEST);
  9741. }
  9742. this._isDepthTestDirty = false;
  9743. }
  9744. // Depth func
  9745. if (this._isDepthFuncDirty) {
  9746. gl.depthFunc(this.depthFunc);
  9747. this._isDepthFuncDirty = false;
  9748. }
  9749. // zOffset
  9750. if (this._isZOffsetDirty) {
  9751. if (this.zOffset) {
  9752. gl.enable(gl.POLYGON_OFFSET_FILL);
  9753. gl.polygonOffset(this.zOffset, 0);
  9754. }
  9755. else {
  9756. gl.disable(gl.POLYGON_OFFSET_FILL);
  9757. }
  9758. this._isZOffsetDirty = false;
  9759. }
  9760. // Front face
  9761. if (this._isFrontFaceDirty) {
  9762. gl.frontFace(this.frontFace);
  9763. this._isFrontFaceDirty = false;
  9764. }
  9765. };
  9766. return _DepthCullingState;
  9767. }());
  9768. BABYLON._DepthCullingState = _DepthCullingState;
  9769. })(BABYLON || (BABYLON = {}));
  9770. //# sourceMappingURL=babylon.depthCullingState.js.map
  9771. var BABYLON;
  9772. (function (BABYLON) {
  9773. var _StencilState = /** @class */ (function () {
  9774. function _StencilState() {
  9775. this._isStencilTestDirty = false;
  9776. this._isStencilMaskDirty = false;
  9777. this._isStencilFuncDirty = false;
  9778. this._isStencilOpDirty = false;
  9779. this.reset();
  9780. }
  9781. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9782. get: function () {
  9783. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9784. },
  9785. enumerable: true,
  9786. configurable: true
  9787. });
  9788. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9789. get: function () {
  9790. return this._stencilFunc;
  9791. },
  9792. set: function (value) {
  9793. if (this._stencilFunc === value) {
  9794. return;
  9795. }
  9796. this._stencilFunc = value;
  9797. this._isStencilFuncDirty = true;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9803. get: function () {
  9804. return this._stencilFuncRef;
  9805. },
  9806. set: function (value) {
  9807. if (this._stencilFuncRef === value) {
  9808. return;
  9809. }
  9810. this._stencilFuncRef = value;
  9811. this._isStencilFuncDirty = true;
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9817. get: function () {
  9818. return this._stencilFuncMask;
  9819. },
  9820. set: function (value) {
  9821. if (this._stencilFuncMask === value) {
  9822. return;
  9823. }
  9824. this._stencilFuncMask = value;
  9825. this._isStencilFuncDirty = true;
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9831. get: function () {
  9832. return this._stencilOpStencilFail;
  9833. },
  9834. set: function (value) {
  9835. if (this._stencilOpStencilFail === value) {
  9836. return;
  9837. }
  9838. this._stencilOpStencilFail = value;
  9839. this._isStencilOpDirty = true;
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9845. get: function () {
  9846. return this._stencilOpDepthFail;
  9847. },
  9848. set: function (value) {
  9849. if (this._stencilOpDepthFail === value) {
  9850. return;
  9851. }
  9852. this._stencilOpDepthFail = value;
  9853. this._isStencilOpDirty = true;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9859. get: function () {
  9860. return this._stencilOpStencilDepthPass;
  9861. },
  9862. set: function (value) {
  9863. if (this._stencilOpStencilDepthPass === value) {
  9864. return;
  9865. }
  9866. this._stencilOpStencilDepthPass = value;
  9867. this._isStencilOpDirty = true;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9873. get: function () {
  9874. return this._stencilMask;
  9875. },
  9876. set: function (value) {
  9877. if (this._stencilMask === value) {
  9878. return;
  9879. }
  9880. this._stencilMask = value;
  9881. this._isStencilMaskDirty = true;
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9887. get: function () {
  9888. return this._stencilTest;
  9889. },
  9890. set: function (value) {
  9891. if (this._stencilTest === value) {
  9892. return;
  9893. }
  9894. this._stencilTest = value;
  9895. this._isStencilTestDirty = true;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. _StencilState.prototype.reset = function () {
  9901. this._stencilTest = false;
  9902. this._stencilMask = 0xFF;
  9903. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9904. this._stencilFuncRef = 1;
  9905. this._stencilFuncMask = 0xFF;
  9906. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9907. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9908. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9909. this._isStencilTestDirty = true;
  9910. this._isStencilMaskDirty = true;
  9911. this._isStencilFuncDirty = true;
  9912. this._isStencilOpDirty = true;
  9913. };
  9914. _StencilState.prototype.apply = function (gl) {
  9915. if (!this.isDirty) {
  9916. return;
  9917. }
  9918. // Stencil test
  9919. if (this._isStencilTestDirty) {
  9920. if (this.stencilTest) {
  9921. gl.enable(gl.STENCIL_TEST);
  9922. }
  9923. else {
  9924. gl.disable(gl.STENCIL_TEST);
  9925. }
  9926. this._isStencilTestDirty = false;
  9927. }
  9928. // Stencil mask
  9929. if (this._isStencilMaskDirty) {
  9930. gl.stencilMask(this.stencilMask);
  9931. this._isStencilMaskDirty = false;
  9932. }
  9933. // Stencil func
  9934. if (this._isStencilFuncDirty) {
  9935. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9936. this._isStencilFuncDirty = false;
  9937. }
  9938. // Stencil op
  9939. if (this._isStencilOpDirty) {
  9940. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9941. this._isStencilOpDirty = false;
  9942. }
  9943. };
  9944. return _StencilState;
  9945. }());
  9946. BABYLON._StencilState = _StencilState;
  9947. })(BABYLON || (BABYLON = {}));
  9948. //# sourceMappingURL=babylon.stencilState.js.map
  9949. var BABYLON;
  9950. (function (BABYLON) {
  9951. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9952. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9953. };
  9954. var compileRawShader = function (gl, source, type) {
  9955. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9956. gl.shaderSource(shader, source);
  9957. gl.compileShader(shader);
  9958. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9959. var log = gl.getShaderInfoLog(shader);
  9960. if (log) {
  9961. throw new Error(log);
  9962. }
  9963. }
  9964. if (!shader) {
  9965. throw new Error("Something went wrong while compile the shader.");
  9966. }
  9967. return shader;
  9968. };
  9969. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9970. var magFilter = gl.NEAREST;
  9971. var minFilter = gl.NEAREST;
  9972. switch (samplingMode) {
  9973. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9974. magFilter = gl.LINEAR;
  9975. if (generateMipMaps) {
  9976. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9977. }
  9978. else {
  9979. minFilter = gl.LINEAR;
  9980. }
  9981. break;
  9982. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9983. magFilter = gl.LINEAR;
  9984. if (generateMipMaps) {
  9985. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9986. }
  9987. else {
  9988. minFilter = gl.LINEAR;
  9989. }
  9990. break;
  9991. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9992. magFilter = gl.NEAREST;
  9993. if (generateMipMaps) {
  9994. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9995. }
  9996. else {
  9997. minFilter = gl.NEAREST;
  9998. }
  9999. break;
  10000. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10001. magFilter = gl.NEAREST;
  10002. if (generateMipMaps) {
  10003. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10004. }
  10005. else {
  10006. minFilter = gl.NEAREST;
  10007. }
  10008. break;
  10009. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10010. magFilter = gl.NEAREST;
  10011. if (generateMipMaps) {
  10012. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10013. }
  10014. else {
  10015. minFilter = gl.LINEAR;
  10016. }
  10017. break;
  10018. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10019. magFilter = gl.NEAREST;
  10020. if (generateMipMaps) {
  10021. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10022. }
  10023. else {
  10024. minFilter = gl.LINEAR;
  10025. }
  10026. break;
  10027. case BABYLON.Texture.NEAREST_LINEAR:
  10028. magFilter = gl.NEAREST;
  10029. minFilter = gl.LINEAR;
  10030. break;
  10031. case BABYLON.Texture.NEAREST_NEAREST:
  10032. magFilter = gl.NEAREST;
  10033. minFilter = gl.NEAREST;
  10034. break;
  10035. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10036. magFilter = gl.LINEAR;
  10037. if (generateMipMaps) {
  10038. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10039. }
  10040. else {
  10041. minFilter = gl.NEAREST;
  10042. }
  10043. break;
  10044. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10045. magFilter = gl.LINEAR;
  10046. if (generateMipMaps) {
  10047. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10048. }
  10049. else {
  10050. minFilter = gl.NEAREST;
  10051. }
  10052. break;
  10053. case BABYLON.Texture.LINEAR_LINEAR:
  10054. magFilter = gl.LINEAR;
  10055. minFilter = gl.LINEAR;
  10056. break;
  10057. case BABYLON.Texture.LINEAR_NEAREST:
  10058. magFilter = gl.LINEAR;
  10059. minFilter = gl.NEAREST;
  10060. break;
  10061. }
  10062. return {
  10063. min: minFilter,
  10064. mag: magFilter
  10065. };
  10066. };
  10067. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10068. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10069. var img;
  10070. var onload = function () {
  10071. loadedImages[index] = img;
  10072. loadedImages._internalCount++;
  10073. if (scene) {
  10074. scene._removePendingData(img);
  10075. }
  10076. if (loadedImages._internalCount === 6) {
  10077. onfinish(loadedImages);
  10078. }
  10079. };
  10080. var onerror = function (message, exception) {
  10081. if (scene) {
  10082. scene._removePendingData(img);
  10083. }
  10084. if (onErrorCallBack) {
  10085. onErrorCallBack(message, exception);
  10086. }
  10087. };
  10088. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10089. if (scene) {
  10090. scene._addPendingData(img);
  10091. }
  10092. };
  10093. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10094. if (onError === void 0) { onError = null; }
  10095. var loadedImages = [];
  10096. loadedImages._internalCount = 0;
  10097. for (var index = 0; index < 6; index++) {
  10098. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10099. }
  10100. };
  10101. var BufferPointer = /** @class */ (function () {
  10102. function BufferPointer() {
  10103. }
  10104. return BufferPointer;
  10105. }());
  10106. var InstancingAttributeInfo = /** @class */ (function () {
  10107. function InstancingAttributeInfo() {
  10108. }
  10109. return InstancingAttributeInfo;
  10110. }());
  10111. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10112. /**
  10113. * Define options used to create a render target texture
  10114. */
  10115. var RenderTargetCreationOptions = /** @class */ (function () {
  10116. function RenderTargetCreationOptions() {
  10117. }
  10118. return RenderTargetCreationOptions;
  10119. }());
  10120. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10121. /**
  10122. * Regroup several parameters relative to the browser in use
  10123. */
  10124. var EngineCapabilities = /** @class */ (function () {
  10125. function EngineCapabilities() {
  10126. }
  10127. return EngineCapabilities;
  10128. }());
  10129. BABYLON.EngineCapabilities = EngineCapabilities;
  10130. /**
  10131. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10132. */
  10133. var Engine = /** @class */ (function () {
  10134. /**
  10135. * @constructor
  10136. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10137. * @param antialias defines enable antialiasing (default: false)
  10138. * @param options defines further options to be sent to the getContext() function
  10139. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10140. */
  10141. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10142. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10143. var _this = this;
  10144. // Public members
  10145. this.forcePOTTextures = false;
  10146. this.isFullscreen = false;
  10147. this.isPointerLock = false;
  10148. this.cullBackFaces = true;
  10149. this.renderEvenInBackground = true;
  10150. this.preventCacheWipeBetweenFrames = false;
  10151. // To enable/disable IDB support and avoid XHR on .manifest
  10152. this.enableOfflineSupport = false;
  10153. this.scenes = new Array();
  10154. this.postProcesses = new Array();
  10155. // Observables
  10156. /**
  10157. * Observable event triggered each time the rendering canvas is resized
  10158. */
  10159. this.onResizeObservable = new BABYLON.Observable();
  10160. /**
  10161. * Observable event triggered each time the canvas loses focus
  10162. */
  10163. this.onCanvasBlurObservable = new BABYLON.Observable();
  10164. /**
  10165. * Observable event triggered each time the canvas gains focus
  10166. */
  10167. this.onCanvasFocusObservable = new BABYLON.Observable();
  10168. /**
  10169. * Observable event triggered each time the canvas receives pointerout event
  10170. */
  10171. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10172. /**
  10173. * Observable event triggered before each texture is initialized
  10174. */
  10175. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10176. //WebVR
  10177. this._vrDisplay = undefined;
  10178. this._vrSupported = false;
  10179. this._vrExclusivePointerMode = false;
  10180. // Uniform buffers list
  10181. this.disableUniformBuffers = false;
  10182. this._uniformBuffers = new Array();
  10183. // Observables
  10184. /**
  10185. * Observable raised when the engine begins a new frame
  10186. */
  10187. this.onBeginFrameObservable = new BABYLON.Observable();
  10188. /**
  10189. * Observable raised when the engine ends the current frame
  10190. */
  10191. this.onEndFrameObservable = new BABYLON.Observable();
  10192. /**
  10193. * Observable raised when the engine is about to compile a shader
  10194. */
  10195. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10196. /**
  10197. * Observable raised when the engine has jsut compiled a shader
  10198. */
  10199. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10200. this._windowIsBackground = false;
  10201. this._webGLVersion = 1.0;
  10202. this._badOS = false;
  10203. this._badDesktopOS = false;
  10204. /**
  10205. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10206. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10207. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10208. */
  10209. this.disableTextureBindingOptimization = false;
  10210. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10211. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10212. this.onVRRequestPresentStart = new BABYLON.Observable();
  10213. this._colorWrite = true;
  10214. this._drawCalls = new BABYLON.PerfCounter();
  10215. this._textureCollisions = new BABYLON.PerfCounter();
  10216. this._renderingQueueLaunched = false;
  10217. this._activeRenderLoops = new Array();
  10218. // Deterministic lockstepMaxSteps
  10219. this._deterministicLockstep = false;
  10220. this._lockstepMaxSteps = 4;
  10221. // Lost context
  10222. this.onContextLostObservable = new BABYLON.Observable();
  10223. this.onContextRestoredObservable = new BABYLON.Observable();
  10224. this._contextWasLost = false;
  10225. this._doNotHandleContextLost = false;
  10226. // FPS
  10227. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10228. this._fps = 60;
  10229. this._deltaTime = 0;
  10230. /**
  10231. * Turn this value on if you want to pause FPS computation when in background
  10232. */
  10233. this.disablePerformanceMonitorInBackground = false;
  10234. // States
  10235. this._depthCullingState = new BABYLON._DepthCullingState();
  10236. this._stencilState = new BABYLON._StencilState();
  10237. this._alphaState = new BABYLON._AlphaState();
  10238. this._alphaMode = Engine.ALPHA_DISABLE;
  10239. // Cache
  10240. this._internalTexturesCache = new Array();
  10241. this._activeChannel = 0;
  10242. this._currentTextureChannel = -1;
  10243. this._boundTexturesCache = {};
  10244. this._compiledEffects = {};
  10245. this._vertexAttribArraysEnabled = [];
  10246. this._uintIndicesCurrentlySet = false;
  10247. this._currentBoundBuffer = new Array();
  10248. this._currentBufferPointers = new Array();
  10249. this._currentInstanceLocations = new Array();
  10250. this._currentInstanceBuffers = new Array();
  10251. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10252. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10253. this._vaoRecordInProgress = false;
  10254. this._mustWipeVertexAttributes = false;
  10255. this._nextFreeTextureSlots = new Array();
  10256. this._maxSimultaneousTextures = 0;
  10257. this._activeRequests = new Array();
  10258. // Hardware supported Compressed Textures
  10259. this._texturesSupported = new Array();
  10260. this._onVRFullScreenTriggered = function () {
  10261. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10262. //get the old size before we change
  10263. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10264. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10265. //get the width and height, change the render size
  10266. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10267. _this.setHardwareScalingLevel(1);
  10268. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10269. }
  10270. else {
  10271. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10272. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10273. }
  10274. };
  10275. this._boundUniforms = {};
  10276. // Register promises
  10277. BABYLON.PromisePolyfill.Apply();
  10278. var canvas = null;
  10279. Engine.Instances.push(this);
  10280. if (!canvasOrContext) {
  10281. return;
  10282. }
  10283. options = options || {};
  10284. if (canvasOrContext.getContext) {
  10285. canvas = canvasOrContext;
  10286. this._renderingCanvas = canvas;
  10287. if (antialias != null) {
  10288. options.antialias = antialias;
  10289. }
  10290. if (options.deterministicLockstep === undefined) {
  10291. options.deterministicLockstep = false;
  10292. }
  10293. if (options.lockstepMaxSteps === undefined) {
  10294. options.lockstepMaxSteps = 4;
  10295. }
  10296. if (options.preserveDrawingBuffer === undefined) {
  10297. options.preserveDrawingBuffer = false;
  10298. }
  10299. if (options.audioEngine === undefined) {
  10300. options.audioEngine = true;
  10301. }
  10302. if (options.stencil === undefined) {
  10303. options.stencil = true;
  10304. }
  10305. this._deterministicLockstep = options.deterministicLockstep;
  10306. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10307. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10308. // Exceptions
  10309. if (navigator && navigator.userAgent) {
  10310. var ua = navigator.userAgent;
  10311. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10312. var exception = _a[_i];
  10313. var key = exception.key;
  10314. var targets = exception.targets;
  10315. if (ua.indexOf(key) > -1) {
  10316. if (exception.capture && exception.captureConstraint) {
  10317. var capture = exception.capture;
  10318. var constraint = exception.captureConstraint;
  10319. var regex = new RegExp(capture);
  10320. var matches = regex.exec(ua);
  10321. if (matches && matches.length > 0) {
  10322. var capturedValue = parseInt(matches[matches.length - 1]);
  10323. if (capturedValue >= constraint) {
  10324. continue;
  10325. }
  10326. }
  10327. }
  10328. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10329. var target = targets_1[_b];
  10330. switch (target) {
  10331. case "uniformBuffer":
  10332. this.disableUniformBuffers = true;
  10333. break;
  10334. case "textureBindingOptimization":
  10335. this.disableTextureBindingOptimization = true;
  10336. break;
  10337. }
  10338. }
  10339. break;
  10340. }
  10341. }
  10342. }
  10343. // GL
  10344. if (!options.disableWebGL2Support) {
  10345. try {
  10346. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10347. if (this._gl) {
  10348. this._webGLVersion = 2.0;
  10349. }
  10350. }
  10351. catch (e) {
  10352. // Do nothing
  10353. }
  10354. }
  10355. if (!this._gl) {
  10356. if (!canvas) {
  10357. throw new Error("The provided canvas is null or undefined.");
  10358. }
  10359. try {
  10360. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10361. }
  10362. catch (e) {
  10363. throw new Error("WebGL not supported");
  10364. }
  10365. }
  10366. if (!this._gl) {
  10367. throw new Error("WebGL not supported");
  10368. }
  10369. this._onCanvasFocus = function () {
  10370. _this.onCanvasFocusObservable.notifyObservers(_this);
  10371. };
  10372. this._onCanvasBlur = function () {
  10373. _this.onCanvasBlurObservable.notifyObservers(_this);
  10374. };
  10375. canvas.addEventListener("focus", this._onCanvasFocus);
  10376. canvas.addEventListener("blur", this._onCanvasBlur);
  10377. this._onBlur = function () {
  10378. if (_this.disablePerformanceMonitorInBackground) {
  10379. _this._performanceMonitor.disable();
  10380. }
  10381. _this._windowIsBackground = true;
  10382. };
  10383. this._onFocus = function () {
  10384. if (_this.disablePerformanceMonitorInBackground) {
  10385. _this._performanceMonitor.enable();
  10386. }
  10387. _this._windowIsBackground = false;
  10388. };
  10389. this._onCanvasPointerOut = function () {
  10390. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10391. };
  10392. window.addEventListener("blur", this._onBlur);
  10393. window.addEventListener("focus", this._onFocus);
  10394. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10395. // Context lost
  10396. if (!this._doNotHandleContextLost) {
  10397. this._onContextLost = function (evt) {
  10398. evt.preventDefault();
  10399. _this._contextWasLost = true;
  10400. BABYLON.Tools.Warn("WebGL context lost.");
  10401. _this.onContextLostObservable.notifyObservers(_this);
  10402. };
  10403. this._onContextRestored = function (evt) {
  10404. // Adding a timeout to avoid race condition at browser level
  10405. setTimeout(function () {
  10406. // Rebuild gl context
  10407. _this._initGLContext();
  10408. // Rebuild effects
  10409. _this._rebuildEffects();
  10410. // Rebuild textures
  10411. _this._rebuildInternalTextures();
  10412. // Rebuild buffers
  10413. _this._rebuildBuffers();
  10414. // Cache
  10415. _this.wipeCaches(true);
  10416. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10417. _this.onContextRestoredObservable.notifyObservers(_this);
  10418. _this._contextWasLost = false;
  10419. }, 0);
  10420. };
  10421. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10422. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10423. }
  10424. }
  10425. else {
  10426. this._gl = canvasOrContext;
  10427. this._renderingCanvas = this._gl.canvas;
  10428. if (this._gl.renderbufferStorageMultisample) {
  10429. this._webGLVersion = 2.0;
  10430. }
  10431. options.stencil = this._gl.getContextAttributes().stencil;
  10432. }
  10433. // Viewport
  10434. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10435. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10436. this.resize();
  10437. this._isStencilEnable = options.stencil ? true : false;
  10438. this._initGLContext();
  10439. if (canvas) {
  10440. // Fullscreen
  10441. this._onFullscreenChange = function () {
  10442. if (document.fullscreen !== undefined) {
  10443. _this.isFullscreen = document.fullscreen;
  10444. }
  10445. else if (document.mozFullScreen !== undefined) {
  10446. _this.isFullscreen = document.mozFullScreen;
  10447. }
  10448. else if (document.webkitIsFullScreen !== undefined) {
  10449. _this.isFullscreen = document.webkitIsFullScreen;
  10450. }
  10451. else if (document.msIsFullScreen !== undefined) {
  10452. _this.isFullscreen = document.msIsFullScreen;
  10453. }
  10454. // Pointer lock
  10455. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10456. canvas.requestPointerLock = canvas.requestPointerLock ||
  10457. canvas.msRequestPointerLock ||
  10458. canvas.mozRequestPointerLock ||
  10459. canvas.webkitRequestPointerLock;
  10460. if (canvas.requestPointerLock) {
  10461. canvas.requestPointerLock();
  10462. }
  10463. }
  10464. };
  10465. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10466. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10467. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10468. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10469. // Pointer lock
  10470. this._onPointerLockChange = function () {
  10471. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10472. document.webkitPointerLockElement === canvas ||
  10473. document.msPointerLockElement === canvas ||
  10474. document.pointerLockElement === canvas);
  10475. };
  10476. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10477. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10478. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10479. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10480. this._onVRDisplayPointerRestricted = function () {
  10481. if (canvas) {
  10482. canvas.requestPointerLock();
  10483. }
  10484. };
  10485. this._onVRDisplayPointerUnrestricted = function () {
  10486. document.exitPointerLock();
  10487. };
  10488. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10489. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10490. }
  10491. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10492. Engine.audioEngine = new BABYLON.AudioEngine();
  10493. }
  10494. // Prepare buffer pointers
  10495. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10496. this._currentBufferPointers[i] = new BufferPointer();
  10497. }
  10498. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10499. // Load WebVR Devices
  10500. if (options.autoEnableWebVR) {
  10501. this.initWebVR();
  10502. }
  10503. // Detect if we are running on a faulty buggy OS.
  10504. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10505. // Detect if we are running on a faulty buggy desktop OS.
  10506. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10507. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10508. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10509. }
  10510. Object.defineProperty(Engine, "LastCreatedEngine", {
  10511. get: function () {
  10512. if (Engine.Instances.length === 0) {
  10513. return null;
  10514. }
  10515. return Engine.Instances[Engine.Instances.length - 1];
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. Object.defineProperty(Engine, "LastCreatedScene", {
  10521. get: function () {
  10522. var lastCreatedEngine = Engine.LastCreatedEngine;
  10523. if (!lastCreatedEngine) {
  10524. return null;
  10525. }
  10526. if (lastCreatedEngine.scenes.length === 0) {
  10527. return null;
  10528. }
  10529. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10530. },
  10531. enumerable: true,
  10532. configurable: true
  10533. });
  10534. /**
  10535. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10536. */
  10537. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10538. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10539. var engine = Engine.Instances[engineIndex];
  10540. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10541. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10542. }
  10543. }
  10544. };
  10545. Object.defineProperty(Engine, "NEVER", {
  10546. get: function () {
  10547. return Engine._NEVER;
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. Object.defineProperty(Engine, "ALWAYS", {
  10553. get: function () {
  10554. return Engine._ALWAYS;
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Object.defineProperty(Engine, "LESS", {
  10560. get: function () {
  10561. return Engine._LESS;
  10562. },
  10563. enumerable: true,
  10564. configurable: true
  10565. });
  10566. Object.defineProperty(Engine, "EQUAL", {
  10567. get: function () {
  10568. return Engine._EQUAL;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. Object.defineProperty(Engine, "LEQUAL", {
  10574. get: function () {
  10575. return Engine._LEQUAL;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(Engine, "GREATER", {
  10581. get: function () {
  10582. return Engine._GREATER;
  10583. },
  10584. enumerable: true,
  10585. configurable: true
  10586. });
  10587. Object.defineProperty(Engine, "GEQUAL", {
  10588. get: function () {
  10589. return Engine._GEQUAL;
  10590. },
  10591. enumerable: true,
  10592. configurable: true
  10593. });
  10594. Object.defineProperty(Engine, "NOTEQUAL", {
  10595. get: function () {
  10596. return Engine._NOTEQUAL;
  10597. },
  10598. enumerable: true,
  10599. configurable: true
  10600. });
  10601. Object.defineProperty(Engine, "KEEP", {
  10602. get: function () {
  10603. return Engine._KEEP;
  10604. },
  10605. enumerable: true,
  10606. configurable: true
  10607. });
  10608. Object.defineProperty(Engine, "REPLACE", {
  10609. get: function () {
  10610. return Engine._REPLACE;
  10611. },
  10612. enumerable: true,
  10613. configurable: true
  10614. });
  10615. Object.defineProperty(Engine, "INCR", {
  10616. get: function () {
  10617. return Engine._INCR;
  10618. },
  10619. enumerable: true,
  10620. configurable: true
  10621. });
  10622. Object.defineProperty(Engine, "DECR", {
  10623. get: function () {
  10624. return Engine._DECR;
  10625. },
  10626. enumerable: true,
  10627. configurable: true
  10628. });
  10629. Object.defineProperty(Engine, "INVERT", {
  10630. get: function () {
  10631. return Engine._INVERT;
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Object.defineProperty(Engine, "INCR_WRAP", {
  10637. get: function () {
  10638. return Engine._INCR_WRAP;
  10639. },
  10640. enumerable: true,
  10641. configurable: true
  10642. });
  10643. Object.defineProperty(Engine, "DECR_WRAP", {
  10644. get: function () {
  10645. return Engine._DECR_WRAP;
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10651. get: function () {
  10652. return Engine._ALPHA_DISABLE;
  10653. },
  10654. enumerable: true,
  10655. configurable: true
  10656. });
  10657. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10658. get: function () {
  10659. return Engine._ALPHA_ONEONE;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(Engine, "ALPHA_ADD", {
  10665. get: function () {
  10666. return Engine._ALPHA_ADD;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10672. get: function () {
  10673. return Engine._ALPHA_COMBINE;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10679. get: function () {
  10680. return Engine._ALPHA_SUBTRACT;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10686. get: function () {
  10687. return Engine._ALPHA_MULTIPLY;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10693. get: function () {
  10694. return Engine._ALPHA_MAXIMIZED;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10700. get: function () {
  10701. return Engine._ALPHA_PREMULTIPLIED;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10707. get: function () {
  10708. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10714. get: function () {
  10715. return Engine._ALPHA_INTERPOLATE;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10721. get: function () {
  10722. return Engine._ALPHA_SCREENMODE;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10728. get: function () {
  10729. return Engine._DELAYLOADSTATE_NONE;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10735. get: function () {
  10736. return Engine._DELAYLOADSTATE_LOADED;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10742. get: function () {
  10743. return Engine._DELAYLOADSTATE_LOADING;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10749. get: function () {
  10750. return Engine._DELAYLOADSTATE_NOTLOADED;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10756. get: function () {
  10757. return Engine._TEXTUREFORMAT_ALPHA;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10763. get: function () {
  10764. return Engine._TEXTUREFORMAT_LUMINANCE;
  10765. },
  10766. enumerable: true,
  10767. configurable: true
  10768. });
  10769. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10770. get: function () {
  10771. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10777. get: function () {
  10778. return Engine._TEXTUREFORMAT_RGB;
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10784. get: function () {
  10785. return Engine._TEXTUREFORMAT_RGBA;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10791. get: function () {
  10792. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10798. get: function () {
  10799. return Engine._TEXTURETYPE_FLOAT;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10805. get: function () {
  10806. return Engine._TEXTURETYPE_HALF_FLOAT;
  10807. },
  10808. enumerable: true,
  10809. configurable: true
  10810. });
  10811. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10812. get: function () {
  10813. return Engine._SCALEMODE_FLOOR;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10819. get: function () {
  10820. return Engine._SCALEMODE_NEAREST;
  10821. },
  10822. enumerable: true,
  10823. configurable: true
  10824. });
  10825. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10826. get: function () {
  10827. return Engine._SCALEMODE_CEILING;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(Engine, "Version", {
  10833. get: function () {
  10834. return "3.2.0-alpha7";
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10840. get: function () {
  10841. return this._vrExclusivePointerMode;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10847. get: function () {
  10848. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10854. get: function () {
  10855. return this._webGLVersion < 2 || this.forcePOTTextures;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine.prototype, "badOS", {
  10861. get: function () {
  10862. return this._badOS;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10868. get: function () {
  10869. return this._badDesktopOS;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10875. get: function () {
  10876. return this._performanceMonitor;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10882. get: function () {
  10883. return this._texturesSupported;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10889. get: function () {
  10890. return this._textureFormatInUse;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Engine.prototype, "currentViewport", {
  10896. get: function () {
  10897. return this._cachedViewport;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10903. // Empty texture
  10904. get: function () {
  10905. if (!this._emptyTexture) {
  10906. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10907. }
  10908. return this._emptyTexture;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10914. get: function () {
  10915. if (!this._emptyTexture3D) {
  10916. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10917. }
  10918. return this._emptyTexture3D;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10924. get: function () {
  10925. if (!this._emptyCubeTexture) {
  10926. var faceData = new Uint8Array(4);
  10927. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10928. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10929. }
  10930. return this._emptyCubeTexture;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Engine.prototype._rebuildInternalTextures = function () {
  10936. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10937. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10938. var internalTexture = currentState_1[_i];
  10939. internalTexture._rebuild();
  10940. }
  10941. };
  10942. Engine.prototype._rebuildEffects = function () {
  10943. for (var key in this._compiledEffects) {
  10944. var effect = this._compiledEffects[key];
  10945. effect._prepareEffect();
  10946. }
  10947. BABYLON.Effect.ResetCache();
  10948. };
  10949. Engine.prototype._rebuildBuffers = function () {
  10950. // Index / Vertex
  10951. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10952. var scene = _a[_i];
  10953. scene.resetCachedMaterial();
  10954. scene._rebuildGeometries();
  10955. scene._rebuildTextures();
  10956. }
  10957. // Uniforms
  10958. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10959. var uniformBuffer = _c[_b];
  10960. uniformBuffer._rebuild();
  10961. }
  10962. };
  10963. Engine.prototype._initGLContext = function () {
  10964. // Caps
  10965. this._caps = new EngineCapabilities();
  10966. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10967. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10968. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10969. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10970. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10971. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10972. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10973. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10974. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10975. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10976. // Infos
  10977. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10978. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10979. if (rendererInfo != null) {
  10980. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10981. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10982. }
  10983. if (!this._glVendor) {
  10984. this._glVendor = "Unknown vendor";
  10985. }
  10986. if (!this._glRenderer) {
  10987. this._glRenderer = "Unknown renderer";
  10988. }
  10989. // Constants
  10990. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10991. if (this._gl.RGBA16F !== 0x881A) {
  10992. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10993. }
  10994. if (this._gl.RGBA32F !== 0x8814) {
  10995. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10996. }
  10997. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10998. this._gl.DEPTH24_STENCIL8 = 35056;
  10999. }
  11000. // Extensions
  11001. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11002. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11003. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11004. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11005. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11006. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11007. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11008. 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');
  11009. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11010. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11011. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11012. this._caps.highPrecisionShaderSupported = true;
  11013. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11014. if (this._caps.timerQuery) {
  11015. if (this._webGLVersion === 1) {
  11016. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11017. }
  11018. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11019. }
  11020. // Checks if some of the format renders first to allow the use of webgl inspector.
  11021. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11022. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11023. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11024. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11025. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11026. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11027. if (this._webGLVersion > 1) {
  11028. this._gl.HALF_FLOAT_OES = 0x140B;
  11029. }
  11030. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11031. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11032. // Draw buffers
  11033. if (this._webGLVersion > 1) {
  11034. this._caps.drawBuffersExtension = true;
  11035. }
  11036. else {
  11037. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11038. if (drawBuffersExtension !== null) {
  11039. this._caps.drawBuffersExtension = true;
  11040. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11041. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11042. for (var i = 0; i < 16; i++) {
  11043. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11044. }
  11045. }
  11046. else {
  11047. this._caps.drawBuffersExtension = false;
  11048. }
  11049. }
  11050. // Depth Texture
  11051. if (this._webGLVersion > 1) {
  11052. this._caps.depthTextureExtension = true;
  11053. }
  11054. else {
  11055. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11056. if (depthTextureExtension != null) {
  11057. this._caps.depthTextureExtension = true;
  11058. }
  11059. }
  11060. // Vertex array object
  11061. if (this._webGLVersion > 1) {
  11062. this._caps.vertexArrayObject = true;
  11063. }
  11064. else {
  11065. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11066. if (vertexArrayObjectExtension != null) {
  11067. this._caps.vertexArrayObject = true;
  11068. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11069. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11070. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11071. }
  11072. else {
  11073. this._caps.vertexArrayObject = false;
  11074. }
  11075. }
  11076. // Instances count
  11077. if (this._webGLVersion > 1) {
  11078. this._caps.instancedArrays = true;
  11079. }
  11080. else {
  11081. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11082. if (instanceExtension != null) {
  11083. this._caps.instancedArrays = true;
  11084. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11085. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11086. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11087. }
  11088. else {
  11089. this._caps.instancedArrays = false;
  11090. }
  11091. }
  11092. // Intelligently add supported compressed formats in order to check for.
  11093. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11094. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11095. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11096. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11097. if (this._caps.astc)
  11098. this.texturesSupported.push('-astc.ktx');
  11099. if (this._caps.s3tc)
  11100. this.texturesSupported.push('-dxt.ktx');
  11101. if (this._caps.pvrtc)
  11102. this.texturesSupported.push('-pvrtc.ktx');
  11103. if (this._caps.etc2)
  11104. this.texturesSupported.push('-etc2.ktx');
  11105. if (this._caps.etc1)
  11106. this.texturesSupported.push('-etc1.ktx');
  11107. if (this._gl.getShaderPrecisionFormat) {
  11108. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11109. if (highp) {
  11110. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11111. }
  11112. }
  11113. // Depth buffer
  11114. this.setDepthBuffer(true);
  11115. this.setDepthFunctionToLessOrEqual();
  11116. this.setDepthWrite(true);
  11117. // Texture maps
  11118. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11119. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11120. this._nextFreeTextureSlots.push(slot);
  11121. }
  11122. };
  11123. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11124. get: function () {
  11125. return this._webGLVersion;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11131. /**
  11132. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11133. */
  11134. get: function () {
  11135. return this._isStencilEnable;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Engine.prototype._prepareWorkingCanvas = function () {
  11141. if (this._workingCanvas) {
  11142. return;
  11143. }
  11144. this._workingCanvas = document.createElement("canvas");
  11145. var context = this._workingCanvas.getContext("2d");
  11146. if (context) {
  11147. this._workingContext = context;
  11148. }
  11149. };
  11150. Engine.prototype.resetTextureCache = function () {
  11151. for (var key in this._boundTexturesCache) {
  11152. var boundTexture = this._boundTexturesCache[key];
  11153. if (boundTexture) {
  11154. this._removeDesignatedSlot(boundTexture);
  11155. }
  11156. this._boundTexturesCache[key] = null;
  11157. }
  11158. if (!this.disableTextureBindingOptimization) {
  11159. this._nextFreeTextureSlots = [];
  11160. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11161. this._nextFreeTextureSlots.push(slot);
  11162. }
  11163. }
  11164. this._currentTextureChannel = -1;
  11165. };
  11166. Engine.prototype.isDeterministicLockStep = function () {
  11167. return this._deterministicLockstep;
  11168. };
  11169. Engine.prototype.getLockstepMaxSteps = function () {
  11170. return this._lockstepMaxSteps;
  11171. };
  11172. Engine.prototype.getGlInfo = function () {
  11173. return {
  11174. vendor: this._glVendor,
  11175. renderer: this._glRenderer,
  11176. version: this._glVersion
  11177. };
  11178. };
  11179. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11180. if (useScreen === void 0) { useScreen = false; }
  11181. var viewport = camera.viewport;
  11182. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11183. };
  11184. Engine.prototype.getRenderWidth = function (useScreen) {
  11185. if (useScreen === void 0) { useScreen = false; }
  11186. if (!useScreen && this._currentRenderTarget) {
  11187. return this._currentRenderTarget.width;
  11188. }
  11189. return this._gl.drawingBufferWidth;
  11190. };
  11191. Engine.prototype.getRenderHeight = function (useScreen) {
  11192. if (useScreen === void 0) { useScreen = false; }
  11193. if (!useScreen && this._currentRenderTarget) {
  11194. return this._currentRenderTarget.height;
  11195. }
  11196. return this._gl.drawingBufferHeight;
  11197. };
  11198. Engine.prototype.getRenderingCanvas = function () {
  11199. return this._renderingCanvas;
  11200. };
  11201. Engine.prototype.getRenderingCanvasClientRect = function () {
  11202. if (!this._renderingCanvas) {
  11203. return null;
  11204. }
  11205. return this._renderingCanvas.getBoundingClientRect();
  11206. };
  11207. Engine.prototype.setHardwareScalingLevel = function (level) {
  11208. this._hardwareScalingLevel = level;
  11209. this.resize();
  11210. };
  11211. Engine.prototype.getHardwareScalingLevel = function () {
  11212. return this._hardwareScalingLevel;
  11213. };
  11214. Engine.prototype.getLoadedTexturesCache = function () {
  11215. return this._internalTexturesCache;
  11216. };
  11217. Engine.prototype.getCaps = function () {
  11218. return this._caps;
  11219. };
  11220. Object.defineProperty(Engine.prototype, "drawCalls", {
  11221. /** The number of draw calls submitted last frame */
  11222. get: function () {
  11223. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11224. return 0;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11230. get: function () {
  11231. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11232. return null;
  11233. },
  11234. enumerable: true,
  11235. configurable: true
  11236. });
  11237. Engine.prototype.getDepthFunction = function () {
  11238. return this._depthCullingState.depthFunc;
  11239. };
  11240. Engine.prototype.setDepthFunction = function (depthFunc) {
  11241. this._depthCullingState.depthFunc = depthFunc;
  11242. };
  11243. Engine.prototype.setDepthFunctionToGreater = function () {
  11244. this._depthCullingState.depthFunc = this._gl.GREATER;
  11245. };
  11246. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11247. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11248. };
  11249. Engine.prototype.setDepthFunctionToLess = function () {
  11250. this._depthCullingState.depthFunc = this._gl.LESS;
  11251. };
  11252. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11253. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11254. };
  11255. Engine.prototype.getStencilBuffer = function () {
  11256. return this._stencilState.stencilTest;
  11257. };
  11258. Engine.prototype.setStencilBuffer = function (enable) {
  11259. this._stencilState.stencilTest = enable;
  11260. };
  11261. Engine.prototype.getStencilMask = function () {
  11262. return this._stencilState.stencilMask;
  11263. };
  11264. Engine.prototype.setStencilMask = function (mask) {
  11265. this._stencilState.stencilMask = mask;
  11266. };
  11267. Engine.prototype.getStencilFunction = function () {
  11268. return this._stencilState.stencilFunc;
  11269. };
  11270. Engine.prototype.getStencilFunctionReference = function () {
  11271. return this._stencilState.stencilFuncRef;
  11272. };
  11273. Engine.prototype.getStencilFunctionMask = function () {
  11274. return this._stencilState.stencilFuncMask;
  11275. };
  11276. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11277. this._stencilState.stencilFunc = stencilFunc;
  11278. };
  11279. Engine.prototype.setStencilFunctionReference = function (reference) {
  11280. this._stencilState.stencilFuncRef = reference;
  11281. };
  11282. Engine.prototype.setStencilFunctionMask = function (mask) {
  11283. this._stencilState.stencilFuncMask = mask;
  11284. };
  11285. Engine.prototype.getStencilOperationFail = function () {
  11286. return this._stencilState.stencilOpStencilFail;
  11287. };
  11288. Engine.prototype.getStencilOperationDepthFail = function () {
  11289. return this._stencilState.stencilOpDepthFail;
  11290. };
  11291. Engine.prototype.getStencilOperationPass = function () {
  11292. return this._stencilState.stencilOpStencilDepthPass;
  11293. };
  11294. Engine.prototype.setStencilOperationFail = function (operation) {
  11295. this._stencilState.stencilOpStencilFail = operation;
  11296. };
  11297. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11298. this._stencilState.stencilOpDepthFail = operation;
  11299. };
  11300. Engine.prototype.setStencilOperationPass = function (operation) {
  11301. this._stencilState.stencilOpStencilDepthPass = operation;
  11302. };
  11303. Engine.prototype.setDitheringState = function (value) {
  11304. if (value) {
  11305. this._gl.enable(this._gl.DITHER);
  11306. }
  11307. else {
  11308. this._gl.disable(this._gl.DITHER);
  11309. }
  11310. };
  11311. Engine.prototype.setRasterizerState = function (value) {
  11312. if (value) {
  11313. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11314. }
  11315. else {
  11316. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11317. }
  11318. };
  11319. /**
  11320. * stop executing a render loop function and remove it from the execution array
  11321. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11322. */
  11323. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11324. if (!renderFunction) {
  11325. this._activeRenderLoops = [];
  11326. return;
  11327. }
  11328. var index = this._activeRenderLoops.indexOf(renderFunction);
  11329. if (index >= 0) {
  11330. this._activeRenderLoops.splice(index, 1);
  11331. }
  11332. };
  11333. Engine.prototype._renderLoop = function () {
  11334. if (!this._contextWasLost) {
  11335. var shouldRender = true;
  11336. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11337. shouldRender = false;
  11338. }
  11339. if (shouldRender) {
  11340. // Start new frame
  11341. this.beginFrame();
  11342. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11343. var renderFunction = this._activeRenderLoops[index];
  11344. renderFunction();
  11345. }
  11346. // Present
  11347. this.endFrame();
  11348. }
  11349. }
  11350. if (this._activeRenderLoops.length > 0) {
  11351. // Register new frame
  11352. var requester = null;
  11353. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11354. requester = this._vrDisplay;
  11355. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11356. }
  11357. else {
  11358. this._renderingQueueLaunched = false;
  11359. }
  11360. };
  11361. /**
  11362. * Register and execute a render loop. The engine can have more than one render function.
  11363. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11364. * @example
  11365. * engine.runRenderLoop(function () {
  11366. * scene.render()
  11367. * })
  11368. */
  11369. Engine.prototype.runRenderLoop = function (renderFunction) {
  11370. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11371. return;
  11372. }
  11373. this._activeRenderLoops.push(renderFunction);
  11374. if (!this._renderingQueueLaunched) {
  11375. this._renderingQueueLaunched = true;
  11376. this._bindedRenderFunction = this._renderLoop.bind(this);
  11377. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11378. }
  11379. };
  11380. /**
  11381. * Toggle full screen mode.
  11382. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11383. * @param {any} options - an options object to be sent to the requestFullscreen function
  11384. */
  11385. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11386. if (this.isFullscreen) {
  11387. BABYLON.Tools.ExitFullscreen();
  11388. }
  11389. else {
  11390. this._pointerLockRequested = requestPointerLock;
  11391. if (this._renderingCanvas) {
  11392. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11393. }
  11394. }
  11395. };
  11396. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11397. if (stencil === void 0) { stencil = false; }
  11398. this.applyStates();
  11399. var mode = 0;
  11400. if (backBuffer && color) {
  11401. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11402. mode |= this._gl.COLOR_BUFFER_BIT;
  11403. }
  11404. if (depth) {
  11405. this._gl.clearDepth(1.0);
  11406. mode |= this._gl.DEPTH_BUFFER_BIT;
  11407. }
  11408. if (stencil) {
  11409. this._gl.clearStencil(0);
  11410. mode |= this._gl.STENCIL_BUFFER_BIT;
  11411. }
  11412. this._gl.clear(mode);
  11413. };
  11414. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11415. var gl = this._gl;
  11416. // Save state
  11417. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11418. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11419. // Change state
  11420. gl.enable(gl.SCISSOR_TEST);
  11421. gl.scissor(x, y, width, height);
  11422. // Clear
  11423. this.clear(clearColor, true, true, true);
  11424. // Restore state
  11425. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11426. if (curScissor === true) {
  11427. gl.enable(gl.SCISSOR_TEST);
  11428. }
  11429. else {
  11430. gl.disable(gl.SCISSOR_TEST);
  11431. }
  11432. };
  11433. /**
  11434. * Set the WebGL's viewport
  11435. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11436. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11437. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11438. */
  11439. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11440. var width = requiredWidth || this.getRenderWidth();
  11441. var height = requiredHeight || this.getRenderHeight();
  11442. var x = viewport.x || 0;
  11443. var y = viewport.y || 0;
  11444. this._cachedViewport = viewport;
  11445. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11446. };
  11447. /**
  11448. * Directly set the WebGL Viewport
  11449. * The x, y, width & height are directly passed to the WebGL call
  11450. * @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.
  11451. */
  11452. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11453. var currentViewport = this._cachedViewport;
  11454. this._cachedViewport = null;
  11455. this._gl.viewport(x, y, width, height);
  11456. return currentViewport;
  11457. };
  11458. Engine.prototype.beginFrame = function () {
  11459. this.onBeginFrameObservable.notifyObservers(this);
  11460. this._measureFps();
  11461. };
  11462. Engine.prototype.endFrame = function () {
  11463. //force a flush in case we are using a bad OS.
  11464. if (this._badOS) {
  11465. this.flushFramebuffer();
  11466. }
  11467. //submit frame to the vr device, if enabled
  11468. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11469. // TODO: We should only submit the frame if we read frameData successfully.
  11470. this._vrDisplay.submitFrame();
  11471. }
  11472. this.onEndFrameObservable.notifyObservers(this);
  11473. };
  11474. /**
  11475. * resize the view according to the canvas' size.
  11476. * @example
  11477. * window.addEventListener("resize", function () {
  11478. * engine.resize();
  11479. * });
  11480. */
  11481. Engine.prototype.resize = function () {
  11482. // We're not resizing the size of the canvas while in VR mode & presenting
  11483. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11484. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11485. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11486. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11487. }
  11488. };
  11489. /**
  11490. * force a specific size of the canvas
  11491. * @param {number} width - the new canvas' width
  11492. * @param {number} height - the new canvas' height
  11493. */
  11494. Engine.prototype.setSize = function (width, height) {
  11495. if (!this._renderingCanvas) {
  11496. return;
  11497. }
  11498. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11499. return;
  11500. }
  11501. this._renderingCanvas.width = width;
  11502. this._renderingCanvas.height = height;
  11503. for (var index = 0; index < this.scenes.length; index++) {
  11504. var scene = this.scenes[index];
  11505. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11506. var cam = scene.cameras[camIndex];
  11507. cam._currentRenderId = 0;
  11508. }
  11509. }
  11510. if (this.onResizeObservable.hasObservers) {
  11511. this.onResizeObservable.notifyObservers(this);
  11512. }
  11513. };
  11514. // WebVR functions
  11515. Engine.prototype.isVRDevicePresent = function () {
  11516. return !!this._vrDisplay;
  11517. };
  11518. Engine.prototype.getVRDevice = function () {
  11519. return this._vrDisplay;
  11520. };
  11521. Engine.prototype.initWebVR = function () {
  11522. var _this = this;
  11523. var notifyObservers = function () {
  11524. var eventArgs = {
  11525. vrDisplay: _this._vrDisplay,
  11526. vrSupported: _this._vrSupported
  11527. };
  11528. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11529. };
  11530. if (!this._onVrDisplayConnect) {
  11531. this._onVrDisplayConnect = function (event) {
  11532. _this._vrDisplay = event.display;
  11533. notifyObservers();
  11534. };
  11535. this._onVrDisplayDisconnect = function () {
  11536. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11537. _this._vrDisplay = undefined;
  11538. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11539. notifyObservers();
  11540. };
  11541. this._onVrDisplayPresentChange = function () {
  11542. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11543. };
  11544. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11545. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11546. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11547. }
  11548. this._getVRDisplays(notifyObservers);
  11549. return this.onVRDisplayChangedObservable;
  11550. };
  11551. Engine.prototype.enableVR = function () {
  11552. var _this = this;
  11553. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11554. var onResolved = function () {
  11555. _this.onVRRequestPresentComplete.notifyObservers(true);
  11556. _this._onVRFullScreenTriggered();
  11557. };
  11558. var onRejected = function () {
  11559. _this.onVRRequestPresentComplete.notifyObservers(false);
  11560. };
  11561. this.onVRRequestPresentStart.notifyObservers(this);
  11562. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11563. }
  11564. };
  11565. Engine.prototype.disableVR = function () {
  11566. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11567. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11568. }
  11569. };
  11570. Engine.prototype._getVRDisplays = function (callback) {
  11571. var _this = this;
  11572. var getWebVRDevices = function (devices) {
  11573. _this._vrSupported = true;
  11574. // note that devices may actually be an empty array. This is fine;
  11575. // we expect this._vrDisplay to be undefined in this case.
  11576. return _this._vrDisplay = devices[0];
  11577. };
  11578. if (navigator.getVRDisplays) {
  11579. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11580. // TODO: System CANNOT support WebVR, despite API presence.
  11581. _this._vrSupported = false;
  11582. callback();
  11583. });
  11584. }
  11585. else {
  11586. // TODO: Browser does not support WebVR
  11587. this._vrDisplay = undefined;
  11588. this._vrSupported = false;
  11589. callback();
  11590. }
  11591. };
  11592. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11593. if (this._currentRenderTarget) {
  11594. this.unBindFramebuffer(this._currentRenderTarget);
  11595. }
  11596. this._currentRenderTarget = texture;
  11597. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11598. var gl = this._gl;
  11599. if (texture.isCube) {
  11600. if (faceIndex === undefined) {
  11601. faceIndex = 0;
  11602. }
  11603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11604. }
  11605. if (this._cachedViewport && !forceFullscreenViewport) {
  11606. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11607. }
  11608. else {
  11609. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11610. }
  11611. this.wipeCaches();
  11612. };
  11613. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11614. if (this._currentFramebuffer !== framebuffer) {
  11615. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11616. this._currentFramebuffer = framebuffer;
  11617. }
  11618. };
  11619. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11620. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11621. this._currentRenderTarget = null;
  11622. // If MSAA, we need to bitblt back to main texture
  11623. var gl = this._gl;
  11624. if (texture._MSAAFramebuffer) {
  11625. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11626. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11627. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11628. }
  11629. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11630. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11631. gl.generateMipmap(gl.TEXTURE_2D);
  11632. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11633. }
  11634. if (onBeforeUnbind) {
  11635. if (texture._MSAAFramebuffer) {
  11636. // Bind the correct framebuffer
  11637. this.bindUnboundFramebuffer(texture._framebuffer);
  11638. }
  11639. onBeforeUnbind();
  11640. }
  11641. this.bindUnboundFramebuffer(null);
  11642. };
  11643. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11644. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11645. this._currentRenderTarget = null;
  11646. // If MSAA, we need to bitblt back to main texture
  11647. var gl = this._gl;
  11648. if (textures[0]._MSAAFramebuffer) {
  11649. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11650. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11651. var attachments = textures[0]._attachments;
  11652. if (!attachments) {
  11653. attachments = new Array(textures.length);
  11654. textures[0]._attachments = attachments;
  11655. }
  11656. for (var i = 0; i < textures.length; i++) {
  11657. var texture = textures[i];
  11658. for (var j = 0; j < attachments.length; j++) {
  11659. attachments[j] = gl.NONE;
  11660. }
  11661. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11662. gl.readBuffer(attachments[i]);
  11663. gl.drawBuffers(attachments);
  11664. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11665. }
  11666. for (var i = 0; i < attachments.length; i++) {
  11667. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11668. }
  11669. gl.drawBuffers(attachments);
  11670. }
  11671. for (var i = 0; i < textures.length; i++) {
  11672. var texture = textures[i];
  11673. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11674. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11675. gl.generateMipmap(gl.TEXTURE_2D);
  11676. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11677. }
  11678. }
  11679. if (onBeforeUnbind) {
  11680. if (textures[0]._MSAAFramebuffer) {
  11681. // Bind the correct framebuffer
  11682. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11683. }
  11684. onBeforeUnbind();
  11685. }
  11686. this.bindUnboundFramebuffer(null);
  11687. };
  11688. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11689. if (texture.generateMipMaps) {
  11690. var gl = this._gl;
  11691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11692. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11694. }
  11695. };
  11696. Engine.prototype.flushFramebuffer = function () {
  11697. this._gl.flush();
  11698. };
  11699. Engine.prototype.restoreDefaultFramebuffer = function () {
  11700. if (this._currentRenderTarget) {
  11701. this.unBindFramebuffer(this._currentRenderTarget);
  11702. }
  11703. else {
  11704. this.bindUnboundFramebuffer(null);
  11705. }
  11706. if (this._cachedViewport) {
  11707. this.setViewport(this._cachedViewport);
  11708. }
  11709. this.wipeCaches();
  11710. };
  11711. // UBOs
  11712. Engine.prototype.createUniformBuffer = function (elements) {
  11713. var ubo = this._gl.createBuffer();
  11714. if (!ubo) {
  11715. throw new Error("Unable to create uniform buffer");
  11716. }
  11717. this.bindUniformBuffer(ubo);
  11718. if (elements instanceof Float32Array) {
  11719. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11720. }
  11721. else {
  11722. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11723. }
  11724. this.bindUniformBuffer(null);
  11725. ubo.references = 1;
  11726. return ubo;
  11727. };
  11728. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11729. var ubo = this._gl.createBuffer();
  11730. if (!ubo) {
  11731. throw new Error("Unable to create dynamic uniform buffer");
  11732. }
  11733. this.bindUniformBuffer(ubo);
  11734. if (elements instanceof Float32Array) {
  11735. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11736. }
  11737. else {
  11738. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11739. }
  11740. this.bindUniformBuffer(null);
  11741. ubo.references = 1;
  11742. return ubo;
  11743. };
  11744. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11745. this.bindUniformBuffer(uniformBuffer);
  11746. if (offset === undefined) {
  11747. offset = 0;
  11748. }
  11749. if (count === undefined) {
  11750. if (elements instanceof Float32Array) {
  11751. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11752. }
  11753. else {
  11754. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11755. }
  11756. }
  11757. else {
  11758. if (elements instanceof Float32Array) {
  11759. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11760. }
  11761. else {
  11762. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11763. }
  11764. }
  11765. this.bindUniformBuffer(null);
  11766. };
  11767. // VBOs
  11768. Engine.prototype._resetVertexBufferBinding = function () {
  11769. this.bindArrayBuffer(null);
  11770. this._cachedVertexBuffers = null;
  11771. };
  11772. Engine.prototype.createVertexBuffer = function (vertices) {
  11773. var vbo = this._gl.createBuffer();
  11774. if (!vbo) {
  11775. throw new Error("Unable to create vertex buffer");
  11776. }
  11777. this.bindArrayBuffer(vbo);
  11778. if (vertices instanceof Float32Array) {
  11779. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11780. }
  11781. else {
  11782. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11783. }
  11784. this._resetVertexBufferBinding();
  11785. vbo.references = 1;
  11786. return vbo;
  11787. };
  11788. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11789. var vbo = this._gl.createBuffer();
  11790. if (!vbo) {
  11791. throw new Error("Unable to create dynamic vertex buffer");
  11792. }
  11793. this.bindArrayBuffer(vbo);
  11794. if (vertices instanceof Float32Array) {
  11795. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11796. }
  11797. else {
  11798. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11799. }
  11800. this._resetVertexBufferBinding();
  11801. vbo.references = 1;
  11802. return vbo;
  11803. };
  11804. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11805. if (offset === void 0) { offset = 0; }
  11806. // Force cache update
  11807. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11808. this.bindIndexBuffer(indexBuffer);
  11809. var arrayBuffer;
  11810. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11811. arrayBuffer = indices;
  11812. }
  11813. else {
  11814. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11815. }
  11816. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11817. this._resetIndexBufferBinding();
  11818. };
  11819. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11820. this.bindArrayBuffer(vertexBuffer);
  11821. if (offset === undefined) {
  11822. offset = 0;
  11823. }
  11824. if (count === undefined) {
  11825. if (vertices instanceof Float32Array) {
  11826. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11827. }
  11828. else {
  11829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11830. }
  11831. }
  11832. else {
  11833. if (vertices instanceof Float32Array) {
  11834. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11835. }
  11836. else {
  11837. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11838. }
  11839. }
  11840. this._resetVertexBufferBinding();
  11841. };
  11842. Engine.prototype._resetIndexBufferBinding = function () {
  11843. this.bindIndexBuffer(null);
  11844. this._cachedIndexBuffer = null;
  11845. };
  11846. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11847. var vbo = this._gl.createBuffer();
  11848. if (!vbo) {
  11849. throw new Error("Unable to create index buffer");
  11850. }
  11851. this.bindIndexBuffer(vbo);
  11852. // Check for 32 bits indices
  11853. var arrayBuffer;
  11854. var need32Bits = false;
  11855. if (indices instanceof Uint16Array) {
  11856. arrayBuffer = indices;
  11857. }
  11858. else {
  11859. //check 32 bit support
  11860. if (this._caps.uintIndices) {
  11861. if (indices instanceof Uint32Array) {
  11862. arrayBuffer = indices;
  11863. need32Bits = true;
  11864. }
  11865. else {
  11866. //number[] or Int32Array, check if 32 bit is necessary
  11867. for (var index = 0; index < indices.length; index++) {
  11868. if (indices[index] > 65535) {
  11869. need32Bits = true;
  11870. break;
  11871. }
  11872. }
  11873. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11874. }
  11875. }
  11876. else {
  11877. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11878. arrayBuffer = new Uint16Array(indices);
  11879. }
  11880. }
  11881. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11882. this._resetIndexBufferBinding();
  11883. vbo.references = 1;
  11884. vbo.is32Bits = need32Bits;
  11885. return vbo;
  11886. };
  11887. Engine.prototype.bindArrayBuffer = function (buffer) {
  11888. if (!this._vaoRecordInProgress) {
  11889. this._unbindVertexArrayObject();
  11890. }
  11891. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11892. };
  11893. Engine.prototype.bindUniformBuffer = function (buffer) {
  11894. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11895. };
  11896. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11897. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11898. };
  11899. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11900. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11901. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11902. };
  11903. ;
  11904. Engine.prototype.bindIndexBuffer = function (buffer) {
  11905. if (!this._vaoRecordInProgress) {
  11906. this._unbindVertexArrayObject();
  11907. }
  11908. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11909. };
  11910. Engine.prototype.bindBuffer = function (buffer, target) {
  11911. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11912. this._gl.bindBuffer(target, buffer);
  11913. this._currentBoundBuffer[target] = buffer;
  11914. }
  11915. };
  11916. Engine.prototype.updateArrayBuffer = function (data) {
  11917. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11918. };
  11919. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11920. var pointer = this._currentBufferPointers[indx];
  11921. var changed = false;
  11922. if (!pointer.active) {
  11923. changed = true;
  11924. pointer.active = true;
  11925. pointer.index = indx;
  11926. pointer.size = size;
  11927. pointer.type = type;
  11928. pointer.normalized = normalized;
  11929. pointer.stride = stride;
  11930. pointer.offset = offset;
  11931. pointer.buffer = buffer;
  11932. }
  11933. else {
  11934. if (pointer.buffer !== buffer) {
  11935. pointer.buffer = buffer;
  11936. changed = true;
  11937. }
  11938. if (pointer.size !== size) {
  11939. pointer.size = size;
  11940. changed = true;
  11941. }
  11942. if (pointer.type !== type) {
  11943. pointer.type = type;
  11944. changed = true;
  11945. }
  11946. if (pointer.normalized !== normalized) {
  11947. pointer.normalized = normalized;
  11948. changed = true;
  11949. }
  11950. if (pointer.stride !== stride) {
  11951. pointer.stride = stride;
  11952. changed = true;
  11953. }
  11954. if (pointer.offset !== offset) {
  11955. pointer.offset = offset;
  11956. changed = true;
  11957. }
  11958. }
  11959. if (changed || this._vaoRecordInProgress) {
  11960. this.bindArrayBuffer(buffer);
  11961. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11962. }
  11963. };
  11964. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11965. if (indexBuffer == null) {
  11966. return;
  11967. }
  11968. if (this._cachedIndexBuffer !== indexBuffer) {
  11969. this._cachedIndexBuffer = indexBuffer;
  11970. this.bindIndexBuffer(indexBuffer);
  11971. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11972. }
  11973. };
  11974. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11975. var attributes = effect.getAttributesNames();
  11976. if (!this._vaoRecordInProgress) {
  11977. this._unbindVertexArrayObject();
  11978. }
  11979. this.unbindAllAttributes();
  11980. for (var index = 0; index < attributes.length; index++) {
  11981. var order = effect.getAttributeLocation(index);
  11982. if (order >= 0) {
  11983. var vertexBuffer = vertexBuffers[attributes[index]];
  11984. if (!vertexBuffer) {
  11985. continue;
  11986. }
  11987. this._gl.enableVertexAttribArray(order);
  11988. if (!this._vaoRecordInProgress) {
  11989. this._vertexAttribArraysEnabled[order] = true;
  11990. }
  11991. var buffer = vertexBuffer.getBuffer();
  11992. if (buffer) {
  11993. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11994. if (vertexBuffer.getIsInstanced()) {
  11995. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11996. if (!this._vaoRecordInProgress) {
  11997. this._currentInstanceLocations.push(order);
  11998. this._currentInstanceBuffers.push(buffer);
  11999. }
  12000. }
  12001. }
  12002. }
  12003. }
  12004. };
  12005. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12006. var vao = this._gl.createVertexArray();
  12007. this._vaoRecordInProgress = true;
  12008. this._gl.bindVertexArray(vao);
  12009. this._mustWipeVertexAttributes = true;
  12010. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12011. this.bindIndexBuffer(indexBuffer);
  12012. this._vaoRecordInProgress = false;
  12013. this._gl.bindVertexArray(null);
  12014. return vao;
  12015. };
  12016. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12017. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12018. this._cachedVertexArrayObject = vertexArrayObject;
  12019. this._gl.bindVertexArray(vertexArrayObject);
  12020. this._cachedVertexBuffers = null;
  12021. this._cachedIndexBuffer = null;
  12022. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12023. this._mustWipeVertexAttributes = true;
  12024. }
  12025. };
  12026. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12027. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12028. this._cachedVertexBuffers = vertexBuffer;
  12029. this._cachedEffectForVertexBuffers = effect;
  12030. var attributesCount = effect.getAttributesCount();
  12031. this._unbindVertexArrayObject();
  12032. this.unbindAllAttributes();
  12033. var offset = 0;
  12034. for (var index = 0; index < attributesCount; index++) {
  12035. if (index < vertexDeclaration.length) {
  12036. var order = effect.getAttributeLocation(index);
  12037. if (order >= 0) {
  12038. this._gl.enableVertexAttribArray(order);
  12039. this._vertexAttribArraysEnabled[order] = true;
  12040. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12041. }
  12042. offset += vertexDeclaration[index] * 4;
  12043. }
  12044. }
  12045. }
  12046. this._bindIndexBufferWithCache(indexBuffer);
  12047. };
  12048. Engine.prototype._unbindVertexArrayObject = function () {
  12049. if (!this._cachedVertexArrayObject) {
  12050. return;
  12051. }
  12052. this._cachedVertexArrayObject = null;
  12053. this._gl.bindVertexArray(null);
  12054. };
  12055. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12056. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12057. this._cachedVertexBuffers = vertexBuffers;
  12058. this._cachedEffectForVertexBuffers = effect;
  12059. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12060. }
  12061. this._bindIndexBufferWithCache(indexBuffer);
  12062. };
  12063. Engine.prototype.unbindInstanceAttributes = function () {
  12064. var boundBuffer;
  12065. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12066. var instancesBuffer = this._currentInstanceBuffers[i];
  12067. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12068. boundBuffer = instancesBuffer;
  12069. this.bindArrayBuffer(instancesBuffer);
  12070. }
  12071. var offsetLocation = this._currentInstanceLocations[i];
  12072. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12073. }
  12074. this._currentInstanceBuffers.length = 0;
  12075. this._currentInstanceLocations.length = 0;
  12076. };
  12077. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12078. this._gl.deleteVertexArray(vao);
  12079. };
  12080. Engine.prototype._releaseBuffer = function (buffer) {
  12081. buffer.references--;
  12082. if (buffer.references === 0) {
  12083. this._gl.deleteBuffer(buffer);
  12084. return true;
  12085. }
  12086. return false;
  12087. };
  12088. Engine.prototype.createInstancesBuffer = function (capacity) {
  12089. var buffer = this._gl.createBuffer();
  12090. if (!buffer) {
  12091. throw new Error("Unable to create instance buffer");
  12092. }
  12093. buffer.capacity = capacity;
  12094. this.bindArrayBuffer(buffer);
  12095. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12096. return buffer;
  12097. };
  12098. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12099. this._gl.deleteBuffer(buffer);
  12100. };
  12101. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12102. this.bindArrayBuffer(instancesBuffer);
  12103. if (data) {
  12104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12105. }
  12106. if (offsetLocations[0].index !== undefined) {
  12107. var stride = 0;
  12108. for (var i = 0; i < offsetLocations.length; i++) {
  12109. var ai = offsetLocations[i];
  12110. stride += ai.attributeSize * 4;
  12111. }
  12112. for (var i = 0; i < offsetLocations.length; i++) {
  12113. var ai = offsetLocations[i];
  12114. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12115. this._gl.enableVertexAttribArray(ai.index);
  12116. this._vertexAttribArraysEnabled[ai.index] = true;
  12117. }
  12118. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12119. this._gl.vertexAttribDivisor(ai.index, 1);
  12120. this._currentInstanceLocations.push(ai.index);
  12121. this._currentInstanceBuffers.push(instancesBuffer);
  12122. }
  12123. }
  12124. else {
  12125. for (var index = 0; index < 4; index++) {
  12126. var offsetLocation = offsetLocations[index];
  12127. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12128. this._gl.enableVertexAttribArray(offsetLocation);
  12129. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12130. }
  12131. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12132. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12133. this._currentInstanceLocations.push(offsetLocation);
  12134. this._currentInstanceBuffers.push(instancesBuffer);
  12135. }
  12136. }
  12137. };
  12138. Engine.prototype.applyStates = function () {
  12139. this._depthCullingState.apply(this._gl);
  12140. this._stencilState.apply(this._gl);
  12141. this._alphaState.apply(this._gl);
  12142. };
  12143. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12144. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12145. };
  12146. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12147. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12148. };
  12149. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12150. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12151. };
  12152. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12153. // Apply states
  12154. this.applyStates();
  12155. this._drawCalls.addCount(1, false);
  12156. // Render
  12157. var drawMode = this.DrawMode(fillMode);
  12158. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12159. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12160. if (instancesCount) {
  12161. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12162. }
  12163. else {
  12164. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12165. }
  12166. };
  12167. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12168. // Apply states
  12169. this.applyStates();
  12170. this._drawCalls.addCount(1, false);
  12171. var drawMode = this.DrawMode(fillMode);
  12172. if (instancesCount) {
  12173. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12174. }
  12175. else {
  12176. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12177. }
  12178. };
  12179. Engine.prototype.DrawMode = function (fillMode) {
  12180. switch (fillMode) {
  12181. // Triangle views
  12182. case BABYLON.Material.TriangleFillMode:
  12183. return this._gl.TRIANGLES;
  12184. case BABYLON.Material.PointFillMode:
  12185. return this._gl.POINTS;
  12186. case BABYLON.Material.WireFrameFillMode:
  12187. return this._gl.LINES;
  12188. // Draw modes
  12189. case BABYLON.Material.PointListDrawMode:
  12190. return this._gl.POINTS;
  12191. case BABYLON.Material.LineListDrawMode:
  12192. return this._gl.LINES;
  12193. case BABYLON.Material.LineLoopDrawMode:
  12194. return this._gl.LINE_LOOP;
  12195. case BABYLON.Material.LineStripDrawMode:
  12196. return this._gl.LINE_STRIP;
  12197. case BABYLON.Material.TriangleStripDrawMode:
  12198. return this._gl.TRIANGLE_STRIP;
  12199. case BABYLON.Material.TriangleFanDrawMode:
  12200. return this._gl.TRIANGLE_FAN;
  12201. default:
  12202. return this._gl.TRIANGLES;
  12203. }
  12204. };
  12205. // Shaders
  12206. Engine.prototype._releaseEffect = function (effect) {
  12207. if (this._compiledEffects[effect._key]) {
  12208. delete this._compiledEffects[effect._key];
  12209. this._deleteProgram(effect.getProgram());
  12210. }
  12211. };
  12212. Engine.prototype._deleteProgram = function (program) {
  12213. if (program) {
  12214. program.__SPECTOR_rebuildProgram = null;
  12215. if (program.transformFeedback) {
  12216. this.deleteTransformFeedback(program.transformFeedback);
  12217. program.transformFeedback = null;
  12218. }
  12219. this._gl.deleteProgram(program);
  12220. }
  12221. };
  12222. /**
  12223. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12224. * @param samplers An array of string used to represent textures
  12225. */
  12226. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12227. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12228. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12229. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12230. if (this._compiledEffects[name]) {
  12231. var compiledEffect = this._compiledEffects[name];
  12232. if (onCompiled && compiledEffect.isReady()) {
  12233. onCompiled(compiledEffect);
  12234. }
  12235. return compiledEffect;
  12236. }
  12237. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12238. effect._key = name;
  12239. this._compiledEffects[name] = effect;
  12240. return effect;
  12241. };
  12242. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12243. if (uniformsNames === void 0) { uniformsNames = []; }
  12244. if (samplers === void 0) { samplers = []; }
  12245. if (defines === void 0) { defines = ""; }
  12246. return this.createEffect({
  12247. vertex: "particles",
  12248. fragmentElement: fragmentName
  12249. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12250. };
  12251. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12252. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12253. context = context || this._gl;
  12254. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12255. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12256. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12257. };
  12258. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12259. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12260. context = context || this._gl;
  12261. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12262. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12263. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12264. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12265. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12266. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12267. return program;
  12268. };
  12269. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12270. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12271. var shaderProgram = context.createProgram();
  12272. if (!shaderProgram) {
  12273. throw new Error("Unable to create program");
  12274. }
  12275. context.attachShader(shaderProgram, vertexShader);
  12276. context.attachShader(shaderProgram, fragmentShader);
  12277. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12278. var transformFeedback = this.createTransformFeedback();
  12279. this.bindTransformFeedback(transformFeedback);
  12280. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12281. shaderProgram.transformFeedback = transformFeedback;
  12282. }
  12283. context.linkProgram(shaderProgram);
  12284. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12285. this.bindTransformFeedback(null);
  12286. }
  12287. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12288. if (!linked) {
  12289. context.validateProgram(shaderProgram);
  12290. var error = context.getProgramInfoLog(shaderProgram);
  12291. if (error) {
  12292. throw new Error(error);
  12293. }
  12294. }
  12295. context.deleteShader(vertexShader);
  12296. context.deleteShader(fragmentShader);
  12297. return shaderProgram;
  12298. };
  12299. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12300. var results = new Array();
  12301. for (var index = 0; index < uniformsNames.length; index++) {
  12302. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12303. }
  12304. return results;
  12305. };
  12306. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12307. var results = [];
  12308. for (var index = 0; index < attributesNames.length; index++) {
  12309. try {
  12310. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12311. }
  12312. catch (e) {
  12313. results.push(-1);
  12314. }
  12315. }
  12316. return results;
  12317. };
  12318. Engine.prototype.enableEffect = function (effect) {
  12319. if (!effect) {
  12320. return;
  12321. }
  12322. // Use program
  12323. this.bindSamplers(effect);
  12324. this._currentEffect = effect;
  12325. if (effect.onBind) {
  12326. effect.onBind(effect);
  12327. }
  12328. effect.onBindObservable.notifyObservers(effect);
  12329. };
  12330. Engine.prototype.setIntArray = function (uniform, array) {
  12331. if (!uniform)
  12332. return;
  12333. this._gl.uniform1iv(uniform, array);
  12334. };
  12335. Engine.prototype.setIntArray2 = function (uniform, array) {
  12336. if (!uniform || array.length % 2 !== 0)
  12337. return;
  12338. this._gl.uniform2iv(uniform, array);
  12339. };
  12340. Engine.prototype.setIntArray3 = function (uniform, array) {
  12341. if (!uniform || array.length % 3 !== 0)
  12342. return;
  12343. this._gl.uniform3iv(uniform, array);
  12344. };
  12345. Engine.prototype.setIntArray4 = function (uniform, array) {
  12346. if (!uniform || array.length % 4 !== 0)
  12347. return;
  12348. this._gl.uniform4iv(uniform, array);
  12349. };
  12350. Engine.prototype.setFloatArray = function (uniform, array) {
  12351. if (!uniform)
  12352. return;
  12353. this._gl.uniform1fv(uniform, array);
  12354. };
  12355. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12356. if (!uniform || array.length % 2 !== 0)
  12357. return;
  12358. this._gl.uniform2fv(uniform, array);
  12359. };
  12360. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12361. if (!uniform || array.length % 3 !== 0)
  12362. return;
  12363. this._gl.uniform3fv(uniform, array);
  12364. };
  12365. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12366. if (!uniform || array.length % 4 !== 0)
  12367. return;
  12368. this._gl.uniform4fv(uniform, array);
  12369. };
  12370. Engine.prototype.setArray = function (uniform, array) {
  12371. if (!uniform)
  12372. return;
  12373. this._gl.uniform1fv(uniform, array);
  12374. };
  12375. Engine.prototype.setArray2 = function (uniform, array) {
  12376. if (!uniform || array.length % 2 !== 0)
  12377. return;
  12378. this._gl.uniform2fv(uniform, array);
  12379. };
  12380. Engine.prototype.setArray3 = function (uniform, array) {
  12381. if (!uniform || array.length % 3 !== 0)
  12382. return;
  12383. this._gl.uniform3fv(uniform, array);
  12384. };
  12385. Engine.prototype.setArray4 = function (uniform, array) {
  12386. if (!uniform || array.length % 4 !== 0)
  12387. return;
  12388. this._gl.uniform4fv(uniform, array);
  12389. };
  12390. Engine.prototype.setMatrices = function (uniform, matrices) {
  12391. if (!uniform)
  12392. return;
  12393. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12394. };
  12395. Engine.prototype.setMatrix = function (uniform, matrix) {
  12396. if (!uniform)
  12397. return;
  12398. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12399. };
  12400. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12401. if (!uniform)
  12402. return;
  12403. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12404. };
  12405. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12406. if (!uniform)
  12407. return;
  12408. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12409. };
  12410. Engine.prototype.setInt = function (uniform, value) {
  12411. if (!uniform)
  12412. return;
  12413. this._gl.uniform1i(uniform, value);
  12414. };
  12415. Engine.prototype.setFloat = function (uniform, value) {
  12416. if (!uniform)
  12417. return;
  12418. this._gl.uniform1f(uniform, value);
  12419. };
  12420. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12421. if (!uniform)
  12422. return;
  12423. this._gl.uniform2f(uniform, x, y);
  12424. };
  12425. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12426. if (!uniform)
  12427. return;
  12428. this._gl.uniform3f(uniform, x, y, z);
  12429. };
  12430. Engine.prototype.setBool = function (uniform, bool) {
  12431. if (!uniform)
  12432. return;
  12433. this._gl.uniform1i(uniform, bool);
  12434. };
  12435. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12436. if (!uniform)
  12437. return;
  12438. this._gl.uniform4f(uniform, x, y, z, w);
  12439. };
  12440. Engine.prototype.setColor3 = function (uniform, color3) {
  12441. if (!uniform)
  12442. return;
  12443. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12444. };
  12445. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12446. if (!uniform)
  12447. return;
  12448. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12449. };
  12450. // States
  12451. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12452. if (zOffset === void 0) { zOffset = 0; }
  12453. if (reverseSide === void 0) { reverseSide = false; }
  12454. // Culling
  12455. if (this._depthCullingState.cull !== culling || force) {
  12456. this._depthCullingState.cull = culling;
  12457. }
  12458. // Cull face
  12459. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12460. if (this._depthCullingState.cullFace !== cullFace || force) {
  12461. this._depthCullingState.cullFace = cullFace;
  12462. }
  12463. // Z offset
  12464. this.setZOffset(zOffset);
  12465. // Front face
  12466. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12467. if (this._depthCullingState.frontFace !== frontFace || force) {
  12468. this._depthCullingState.frontFace = frontFace;
  12469. }
  12470. };
  12471. Engine.prototype.setZOffset = function (value) {
  12472. this._depthCullingState.zOffset = value;
  12473. };
  12474. Engine.prototype.getZOffset = function () {
  12475. return this._depthCullingState.zOffset;
  12476. };
  12477. Engine.prototype.setDepthBuffer = function (enable) {
  12478. this._depthCullingState.depthTest = enable;
  12479. };
  12480. Engine.prototype.getDepthWrite = function () {
  12481. return this._depthCullingState.depthMask;
  12482. };
  12483. Engine.prototype.setDepthWrite = function (enable) {
  12484. this._depthCullingState.depthMask = enable;
  12485. };
  12486. Engine.prototype.setColorWrite = function (enable) {
  12487. this._gl.colorMask(enable, enable, enable, enable);
  12488. this._colorWrite = enable;
  12489. };
  12490. Engine.prototype.getColorWrite = function () {
  12491. return this._colorWrite;
  12492. };
  12493. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12494. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12495. };
  12496. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12497. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12498. if (this._alphaMode === mode) {
  12499. return;
  12500. }
  12501. switch (mode) {
  12502. case Engine.ALPHA_DISABLE:
  12503. this._alphaState.alphaBlend = false;
  12504. break;
  12505. case Engine.ALPHA_PREMULTIPLIED:
  12506. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12507. this._alphaState.alphaBlend = true;
  12508. break;
  12509. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12510. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12511. this._alphaState.alphaBlend = true;
  12512. break;
  12513. case Engine.ALPHA_COMBINE:
  12514. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12515. this._alphaState.alphaBlend = true;
  12516. break;
  12517. case Engine.ALPHA_ONEONE:
  12518. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12519. this._alphaState.alphaBlend = true;
  12520. break;
  12521. case Engine.ALPHA_ADD:
  12522. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12523. this._alphaState.alphaBlend = true;
  12524. break;
  12525. case Engine.ALPHA_SUBTRACT:
  12526. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12527. this._alphaState.alphaBlend = true;
  12528. break;
  12529. case Engine.ALPHA_MULTIPLY:
  12530. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12531. this._alphaState.alphaBlend = true;
  12532. break;
  12533. case Engine.ALPHA_MAXIMIZED:
  12534. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12535. this._alphaState.alphaBlend = true;
  12536. break;
  12537. case Engine.ALPHA_INTERPOLATE:
  12538. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12539. this._alphaState.alphaBlend = true;
  12540. break;
  12541. case Engine.ALPHA_SCREENMODE:
  12542. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12543. this._alphaState.alphaBlend = true;
  12544. break;
  12545. }
  12546. if (!noDepthWriteChange) {
  12547. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12548. }
  12549. this._alphaMode = mode;
  12550. };
  12551. Engine.prototype.getAlphaMode = function () {
  12552. return this._alphaMode;
  12553. };
  12554. // Textures
  12555. Engine.prototype.wipeCaches = function (bruteForce) {
  12556. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12557. return;
  12558. }
  12559. this._currentEffect = null;
  12560. // 6/8/2017: deltakosh: Should not be required anymore.
  12561. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12562. if (bruteForce) {
  12563. this.resetTextureCache();
  12564. this._currentProgram = null;
  12565. this._stencilState.reset();
  12566. this._depthCullingState.reset();
  12567. this.setDepthFunctionToLessOrEqual();
  12568. this._alphaState.reset();
  12569. }
  12570. this._resetVertexBufferBinding();
  12571. this._cachedIndexBuffer = null;
  12572. this._cachedEffectForVertexBuffers = null;
  12573. this._unbindVertexArrayObject();
  12574. this.bindIndexBuffer(null);
  12575. };
  12576. /**
  12577. * Set the compressed texture format to use, based on the formats you have, and the formats
  12578. * supported by the hardware / browser.
  12579. *
  12580. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12581. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12582. * to API arguments needed to compressed textures. This puts the burden on the container
  12583. * generator to house the arcane code for determining these for current & future formats.
  12584. *
  12585. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12586. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12587. *
  12588. * Note: The result of this call is not taken into account when a texture is base64.
  12589. *
  12590. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12591. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12592. *
  12593. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12594. * @returns The extension selected.
  12595. */
  12596. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12597. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12598. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12599. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12600. return this._textureFormatInUse = this._texturesSupported[i];
  12601. }
  12602. }
  12603. }
  12604. // actively set format to nothing, to allow this to be called more than once
  12605. // and possibly fail the 2nd time
  12606. this._textureFormatInUse = null;
  12607. return null;
  12608. };
  12609. Engine.prototype._createTexture = function () {
  12610. var texture = this._gl.createTexture();
  12611. if (!texture) {
  12612. throw new Error("Unable to create texture");
  12613. }
  12614. return texture;
  12615. };
  12616. /**
  12617. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12618. * @param {string} urlArg- This contains one of the following:
  12619. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12620. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12621. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12622. *
  12623. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12624. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12625. * @param {Scene} scene- Needed for loading to the correct scene.
  12626. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12627. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12628. * @param {callback} onError- Optional callback to be called upon failure.
  12629. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12630. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12631. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12632. *
  12633. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12634. */
  12635. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12636. var _this = this;
  12637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12638. if (onLoad === void 0) { onLoad = null; }
  12639. if (onError === void 0) { onError = null; }
  12640. if (buffer === void 0) { buffer = null; }
  12641. if (fallBack === void 0) { fallBack = null; }
  12642. if (format === void 0) { format = null; }
  12643. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12644. var fromData = url.substr(0, 5) === "data:";
  12645. var fromBlob = url.substr(0, 5) === "blob:";
  12646. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12647. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12648. // establish the file extension, if possible
  12649. var lastDot = url.lastIndexOf('.');
  12650. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12651. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12652. var isTGA = (extension.indexOf(".tga") === 0);
  12653. // determine if a ktx file should be substituted
  12654. var isKTX = false;
  12655. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12656. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12657. isKTX = true;
  12658. }
  12659. if (scene) {
  12660. scene._addPendingData(texture);
  12661. }
  12662. texture.url = url;
  12663. texture.generateMipMaps = !noMipmap;
  12664. texture.samplingMode = samplingMode;
  12665. texture.invertY = invertY;
  12666. if (!this._doNotHandleContextLost) {
  12667. // Keep a link to the buffer only if we plan to handle context lost
  12668. texture._buffer = buffer;
  12669. }
  12670. var onLoadObserver = null;
  12671. if (onLoad && !fallBack) {
  12672. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12673. }
  12674. if (!fallBack)
  12675. this._internalTexturesCache.push(texture);
  12676. var onerror = function (message, exception) {
  12677. if (scene) {
  12678. scene._removePendingData(texture);
  12679. }
  12680. if (onLoadObserver) {
  12681. texture.onLoadedObservable.remove(onLoadObserver);
  12682. }
  12683. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12684. if (isKTX) {
  12685. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12686. }
  12687. else if (BABYLON.Tools.UseFallbackTexture) {
  12688. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12689. }
  12690. if (onError) {
  12691. onError(message || "Unknown error", exception);
  12692. }
  12693. };
  12694. var callback = null;
  12695. // processing for non-image formats
  12696. if (isKTX || isTGA || isDDS) {
  12697. if (isKTX) {
  12698. callback = function (data) {
  12699. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12700. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12701. ktx.uploadLevels(_this._gl, !noMipmap);
  12702. return false;
  12703. }, samplingMode);
  12704. };
  12705. }
  12706. else if (isTGA) {
  12707. callback = function (arrayBuffer) {
  12708. var data = new Uint8Array(arrayBuffer);
  12709. var header = BABYLON.TGATools.GetTGAHeader(data);
  12710. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12711. BABYLON.TGATools.UploadContent(_this._gl, data);
  12712. return false;
  12713. }, samplingMode);
  12714. };
  12715. }
  12716. else if (isDDS) {
  12717. callback = function (data) {
  12718. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12719. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12720. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12721. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12722. return false;
  12723. }, samplingMode);
  12724. };
  12725. }
  12726. if (!buffer) {
  12727. this._loadFile(url, function (data) {
  12728. if (callback) {
  12729. callback(data);
  12730. }
  12731. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12732. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12733. });
  12734. }
  12735. else {
  12736. if (callback) {
  12737. callback(buffer);
  12738. }
  12739. }
  12740. // image format processing
  12741. }
  12742. else {
  12743. var onload = function (img) {
  12744. if (fromBlob && !_this._doNotHandleContextLost) {
  12745. // We need to store the image if we need to rebuild the texture
  12746. // in case of a webgl context lost
  12747. texture._buffer = img;
  12748. }
  12749. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12750. var gl = _this._gl;
  12751. var isPot = (img.width === potWidth && img.height === potHeight);
  12752. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12753. if (isPot) {
  12754. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12755. return false;
  12756. }
  12757. // Using shaders to rescale because canvas.drawImage is lossy
  12758. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12759. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12760. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12765. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12766. _this._releaseTexture(source);
  12767. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12768. continuationCallback();
  12769. });
  12770. return true;
  12771. }, samplingMode);
  12772. };
  12773. if (!fromData || isBase64)
  12774. if (buffer instanceof HTMLImageElement) {
  12775. onload(buffer);
  12776. }
  12777. else {
  12778. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12779. }
  12780. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12781. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12782. else
  12783. onload(buffer);
  12784. }
  12785. return texture;
  12786. };
  12787. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12788. var _this = this;
  12789. var rtt = this.createRenderTargetTexture({
  12790. width: destination.width,
  12791. height: destination.height,
  12792. }, {
  12793. generateMipMaps: false,
  12794. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12795. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12796. generateDepthBuffer: false,
  12797. generateStencilBuffer: false
  12798. });
  12799. if (!this._rescalePostProcess) {
  12800. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12801. }
  12802. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12803. _this._rescalePostProcess.onApply = function (effect) {
  12804. effect._bindTexture("textureSampler", source);
  12805. };
  12806. var hostingScene = scene;
  12807. if (!hostingScene) {
  12808. hostingScene = _this.scenes[_this.scenes.length - 1];
  12809. }
  12810. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12811. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12812. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12813. _this.unBindFramebuffer(rtt);
  12814. _this._releaseTexture(rtt);
  12815. if (onComplete) {
  12816. onComplete();
  12817. }
  12818. });
  12819. };
  12820. Engine.prototype._getInternalFormat = function (format) {
  12821. var internalFormat = this._gl.RGBA;
  12822. switch (format) {
  12823. case Engine.TEXTUREFORMAT_ALPHA:
  12824. internalFormat = this._gl.ALPHA;
  12825. break;
  12826. case Engine.TEXTUREFORMAT_LUMINANCE:
  12827. internalFormat = this._gl.LUMINANCE;
  12828. break;
  12829. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12830. internalFormat = this._gl.LUMINANCE_ALPHA;
  12831. break;
  12832. case Engine.TEXTUREFORMAT_RGB:
  12833. internalFormat = this._gl.RGB;
  12834. break;
  12835. case Engine.TEXTUREFORMAT_RGBA:
  12836. internalFormat = this._gl.RGBA;
  12837. break;
  12838. }
  12839. return internalFormat;
  12840. };
  12841. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12842. if (compression === void 0) { compression = null; }
  12843. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12844. if (!texture) {
  12845. return;
  12846. }
  12847. var internalFormat = this._getInternalFormat(format);
  12848. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12849. var textureType = this._getWebGLTextureType(type);
  12850. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12851. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12852. if (!this._doNotHandleContextLost) {
  12853. texture._bufferView = data;
  12854. texture.format = format;
  12855. texture.type = type;
  12856. texture.invertY = invertY;
  12857. texture._compression = compression;
  12858. }
  12859. if (texture.width % 4 !== 0) {
  12860. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12861. }
  12862. if (compression && data) {
  12863. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12864. }
  12865. else {
  12866. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12867. }
  12868. if (texture.generateMipMaps) {
  12869. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12870. }
  12871. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12872. // this.resetTextureCache();
  12873. texture.isReady = true;
  12874. };
  12875. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12876. if (compression === void 0) { compression = null; }
  12877. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12878. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12879. texture.baseWidth = width;
  12880. texture.baseHeight = height;
  12881. texture.width = width;
  12882. texture.height = height;
  12883. texture.format = format;
  12884. texture.generateMipMaps = generateMipMaps;
  12885. texture.samplingMode = samplingMode;
  12886. texture.invertY = invertY;
  12887. texture._compression = compression;
  12888. texture.type = type;
  12889. if (!this._doNotHandleContextLost) {
  12890. texture._bufferView = data;
  12891. }
  12892. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12893. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12894. // Filters
  12895. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12898. if (generateMipMaps) {
  12899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12900. }
  12901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12902. this._internalTexturesCache.push(texture);
  12903. return texture;
  12904. };
  12905. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12906. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12907. texture.baseWidth = width;
  12908. texture.baseHeight = height;
  12909. if (generateMipMaps) {
  12910. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12911. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12912. }
  12913. // this.resetTextureCache();
  12914. texture.width = width;
  12915. texture.height = height;
  12916. texture.isReady = false;
  12917. texture.generateMipMaps = generateMipMaps;
  12918. texture.samplingMode = samplingMode;
  12919. this.updateTextureSamplingMode(samplingMode, texture);
  12920. this._internalTexturesCache.push(texture);
  12921. return texture;
  12922. };
  12923. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12924. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12925. if (texture.isCube) {
  12926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12927. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12929. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12930. }
  12931. else if (texture.is3D) {
  12932. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12933. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12934. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12935. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12936. }
  12937. else {
  12938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12939. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12940. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12941. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12942. }
  12943. texture.samplingMode = samplingMode;
  12944. };
  12945. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12946. if (premulAlpha === void 0) { premulAlpha = false; }
  12947. if (!texture) {
  12948. return;
  12949. }
  12950. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12951. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12952. if (premulAlpha) {
  12953. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12954. }
  12955. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12956. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12957. if (texture.generateMipMaps) {
  12958. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12959. }
  12960. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12961. if (premulAlpha) {
  12962. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12963. }
  12964. texture.isReady = true;
  12965. };
  12966. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12967. if (!texture || texture._isDisabled) {
  12968. return;
  12969. }
  12970. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12971. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12972. try {
  12973. // Testing video texture support
  12974. if (this._videoTextureSupported === undefined) {
  12975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12976. if (this._gl.getError() !== 0) {
  12977. this._videoTextureSupported = false;
  12978. }
  12979. else {
  12980. this._videoTextureSupported = true;
  12981. }
  12982. }
  12983. // Copy video through the current working canvas if video texture is not supported
  12984. if (!this._videoTextureSupported) {
  12985. if (!texture._workingCanvas) {
  12986. texture._workingCanvas = document.createElement("canvas");
  12987. var context = texture._workingCanvas.getContext("2d");
  12988. if (!context) {
  12989. throw new Error("Unable to get 2d context");
  12990. }
  12991. texture._workingContext = context;
  12992. texture._workingCanvas.width = texture.width;
  12993. texture._workingCanvas.height = texture.height;
  12994. }
  12995. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12996. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12997. }
  12998. else {
  12999. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13000. }
  13001. if (texture.generateMipMaps) {
  13002. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13003. }
  13004. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13005. // this.resetTextureCache();
  13006. texture.isReady = true;
  13007. }
  13008. catch (ex) {
  13009. // Something unexpected
  13010. // Let's disable the texture
  13011. texture._isDisabled = true;
  13012. }
  13013. };
  13014. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13015. var fullOptions = new RenderTargetCreationOptions();
  13016. if (options !== undefined && typeof options === "object") {
  13017. fullOptions.generateMipMaps = options.generateMipMaps;
  13018. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13019. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13020. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13021. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13022. }
  13023. else {
  13024. fullOptions.generateMipMaps = options;
  13025. fullOptions.generateDepthBuffer = true;
  13026. fullOptions.generateStencilBuffer = false;
  13027. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13028. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13029. }
  13030. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13031. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13032. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13033. }
  13034. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13035. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13036. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13037. }
  13038. var gl = this._gl;
  13039. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13040. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13041. var width = size.width || size;
  13042. var height = size.height || size;
  13043. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13044. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13045. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13046. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13047. }
  13048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13052. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13053. // Create the framebuffer
  13054. var framebuffer = gl.createFramebuffer();
  13055. this.bindUnboundFramebuffer(framebuffer);
  13056. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13057. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13058. if (fullOptions.generateMipMaps) {
  13059. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13060. }
  13061. // Unbind
  13062. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13063. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13064. this.bindUnboundFramebuffer(null);
  13065. texture._framebuffer = framebuffer;
  13066. texture.baseWidth = width;
  13067. texture.baseHeight = height;
  13068. texture.width = width;
  13069. texture.height = height;
  13070. texture.isReady = true;
  13071. texture.samples = 1;
  13072. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13073. texture.samplingMode = fullOptions.samplingMode;
  13074. texture.type = fullOptions.type;
  13075. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13076. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13077. // this.resetTextureCache();
  13078. this._internalTexturesCache.push(texture);
  13079. return texture;
  13080. };
  13081. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13082. var generateMipMaps = false;
  13083. var generateDepthBuffer = true;
  13084. var generateStencilBuffer = false;
  13085. var generateDepthTexture = false;
  13086. var textureCount = 1;
  13087. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13088. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13089. var types = [], samplingModes = [];
  13090. if (options !== undefined) {
  13091. generateMipMaps = options.generateMipMaps;
  13092. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13093. generateStencilBuffer = options.generateStencilBuffer;
  13094. generateDepthTexture = options.generateDepthTexture;
  13095. textureCount = options.textureCount || 1;
  13096. if (options.types) {
  13097. types = options.types;
  13098. }
  13099. if (options.samplingModes) {
  13100. samplingModes = options.samplingModes;
  13101. }
  13102. }
  13103. var gl = this._gl;
  13104. // Create the framebuffer
  13105. var framebuffer = gl.createFramebuffer();
  13106. this.bindUnboundFramebuffer(framebuffer);
  13107. var width = size.width || size;
  13108. var height = size.height || size;
  13109. var textures = [];
  13110. var attachments = [];
  13111. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13112. for (var i = 0; i < textureCount; i++) {
  13113. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13114. var type = types[i] || defaultType;
  13115. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13116. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13117. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13118. }
  13119. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13120. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13121. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13122. }
  13123. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13124. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13125. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13126. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13127. }
  13128. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13129. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13130. textures.push(texture);
  13131. attachments.push(attachment);
  13132. gl.activeTexture(gl["TEXTURE" + i]);
  13133. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13138. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13139. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13140. if (generateMipMaps) {
  13141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13142. }
  13143. // Unbind
  13144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13145. texture._framebuffer = framebuffer;
  13146. texture._depthStencilBuffer = depthStencilBuffer;
  13147. texture.baseWidth = width;
  13148. texture.baseHeight = height;
  13149. texture.width = width;
  13150. texture.height = height;
  13151. texture.isReady = true;
  13152. texture.samples = 1;
  13153. texture.generateMipMaps = generateMipMaps;
  13154. texture.samplingMode = samplingMode;
  13155. texture.type = type;
  13156. texture._generateDepthBuffer = generateDepthBuffer;
  13157. texture._generateStencilBuffer = generateStencilBuffer;
  13158. texture._attachments = attachments;
  13159. this._internalTexturesCache.push(texture);
  13160. }
  13161. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13162. // Depth texture
  13163. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13164. gl.activeTexture(gl.TEXTURE0);
  13165. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13170. 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);
  13171. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13172. depthTexture._framebuffer = framebuffer;
  13173. depthTexture.baseWidth = width;
  13174. depthTexture.baseHeight = height;
  13175. depthTexture.width = width;
  13176. depthTexture.height = height;
  13177. depthTexture.isReady = true;
  13178. depthTexture.samples = 1;
  13179. depthTexture.generateMipMaps = generateMipMaps;
  13180. depthTexture.samplingMode = gl.NEAREST;
  13181. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13182. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13183. textures.push(depthTexture);
  13184. this._internalTexturesCache.push(depthTexture);
  13185. }
  13186. gl.drawBuffers(attachments);
  13187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13188. this.bindUnboundFramebuffer(null);
  13189. this.resetTextureCache();
  13190. return textures;
  13191. };
  13192. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13193. if (samples === void 0) { samples = 1; }
  13194. var depthStencilBuffer = null;
  13195. var gl = this._gl;
  13196. // Create the depth/stencil buffer
  13197. if (generateStencilBuffer) {
  13198. depthStencilBuffer = gl.createRenderbuffer();
  13199. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13200. if (samples > 1) {
  13201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13202. }
  13203. else {
  13204. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13205. }
  13206. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13207. }
  13208. else if (generateDepthBuffer) {
  13209. depthStencilBuffer = gl.createRenderbuffer();
  13210. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13211. if (samples > 1) {
  13212. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13213. }
  13214. else {
  13215. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13216. }
  13217. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13218. }
  13219. return depthStencilBuffer;
  13220. };
  13221. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13222. if (this.webGLVersion < 2 || !texture) {
  13223. return 1;
  13224. }
  13225. if (texture.samples === samples) {
  13226. return samples;
  13227. }
  13228. var gl = this._gl;
  13229. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13230. // Dispose previous render buffers
  13231. if (texture._depthStencilBuffer) {
  13232. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13233. texture._depthStencilBuffer = null;
  13234. }
  13235. if (texture._MSAAFramebuffer) {
  13236. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13237. texture._MSAAFramebuffer = null;
  13238. }
  13239. if (texture._MSAARenderBuffer) {
  13240. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13241. texture._MSAARenderBuffer = null;
  13242. }
  13243. if (samples > 1) {
  13244. var framebuffer = gl.createFramebuffer();
  13245. if (!framebuffer) {
  13246. throw new Error("Unable to create multi sampled framebuffer");
  13247. }
  13248. texture._MSAAFramebuffer = framebuffer;
  13249. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13250. var colorRenderbuffer = gl.createRenderbuffer();
  13251. if (!colorRenderbuffer) {
  13252. throw new Error("Unable to create multi sampled framebuffer");
  13253. }
  13254. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13255. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13256. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13257. texture._MSAARenderBuffer = colorRenderbuffer;
  13258. }
  13259. else {
  13260. this.bindUnboundFramebuffer(texture._framebuffer);
  13261. }
  13262. texture.samples = samples;
  13263. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13264. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13265. this.bindUnboundFramebuffer(null);
  13266. return samples;
  13267. };
  13268. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13269. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13270. return 1;
  13271. }
  13272. if (textures[0].samples === samples) {
  13273. return samples;
  13274. }
  13275. var gl = this._gl;
  13276. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13277. // Dispose previous render buffers
  13278. if (textures[0]._depthStencilBuffer) {
  13279. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13280. textures[0]._depthStencilBuffer = null;
  13281. }
  13282. if (textures[0]._MSAAFramebuffer) {
  13283. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13284. textures[0]._MSAAFramebuffer = null;
  13285. }
  13286. for (var i = 0; i < textures.length; i++) {
  13287. if (textures[i]._MSAARenderBuffer) {
  13288. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13289. textures[i]._MSAARenderBuffer = null;
  13290. }
  13291. }
  13292. if (samples > 1) {
  13293. var framebuffer = gl.createFramebuffer();
  13294. if (!framebuffer) {
  13295. throw new Error("Unable to create multi sampled framebuffer");
  13296. }
  13297. this.bindUnboundFramebuffer(framebuffer);
  13298. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13299. var attachments = [];
  13300. for (var i = 0; i < textures.length; i++) {
  13301. var texture = textures[i];
  13302. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13303. var colorRenderbuffer = gl.createRenderbuffer();
  13304. if (!colorRenderbuffer) {
  13305. throw new Error("Unable to create multi sampled framebuffer");
  13306. }
  13307. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13308. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13309. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13310. texture._MSAAFramebuffer = framebuffer;
  13311. texture._MSAARenderBuffer = colorRenderbuffer;
  13312. texture.samples = samples;
  13313. texture._depthStencilBuffer = depthStencilBuffer;
  13314. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13315. attachments.push(attachment);
  13316. }
  13317. gl.drawBuffers(attachments);
  13318. }
  13319. else {
  13320. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13321. }
  13322. this.bindUnboundFramebuffer(null);
  13323. return samples;
  13324. };
  13325. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13326. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13327. };
  13328. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13329. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13330. };
  13331. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13332. var gl = this._gl;
  13333. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13334. var generateMipMaps = true;
  13335. var generateDepthBuffer = true;
  13336. var generateStencilBuffer = false;
  13337. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13338. if (options !== undefined) {
  13339. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13340. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13341. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13342. if (options.samplingMode !== undefined) {
  13343. samplingMode = options.samplingMode;
  13344. }
  13345. }
  13346. texture.isCube = true;
  13347. texture.generateMipMaps = generateMipMaps;
  13348. texture.samples = 1;
  13349. texture.samplingMode = samplingMode;
  13350. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13351. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13352. for (var face = 0; face < 6; face++) {
  13353. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13354. }
  13355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13359. // Create the framebuffer
  13360. var framebuffer = gl.createFramebuffer();
  13361. this.bindUnboundFramebuffer(framebuffer);
  13362. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13363. // Mipmaps
  13364. if (texture.generateMipMaps) {
  13365. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13366. }
  13367. // Unbind
  13368. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13369. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13370. this.bindUnboundFramebuffer(null);
  13371. texture._framebuffer = framebuffer;
  13372. texture.width = size;
  13373. texture.height = size;
  13374. texture.isReady = true;
  13375. //this.resetTextureCache();
  13376. this._internalTexturesCache.push(texture);
  13377. return texture;
  13378. };
  13379. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13380. var _this = this;
  13381. if (onLoad === void 0) { onLoad = null; }
  13382. if (onError === void 0) { onError = null; }
  13383. if (forcedExtension === void 0) { forcedExtension = null; }
  13384. var callback = function (loadData) {
  13385. if (!loadData) {
  13386. if (onLoad) {
  13387. onLoad(null);
  13388. }
  13389. return;
  13390. }
  13391. var texture = loadData.texture;
  13392. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13393. texture._lodGenerationScale = scale;
  13394. texture._lodGenerationOffset = offset;
  13395. if (_this._caps.textureLOD) {
  13396. // Do not add extra process if texture lod is supported.
  13397. if (onLoad) {
  13398. onLoad(texture);
  13399. }
  13400. return;
  13401. }
  13402. var mipSlices = 3;
  13403. var gl = _this._gl;
  13404. var width = loadData.width;
  13405. if (!width) {
  13406. return;
  13407. }
  13408. var textures = [];
  13409. for (var i = 0; i < mipSlices; i++) {
  13410. //compute LOD from even spacing in smoothness (matching shader calculation)
  13411. var smoothness = i / (mipSlices - 1);
  13412. var roughness = 1 - smoothness;
  13413. var minLODIndex = offset; // roughness = 0
  13414. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13415. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13416. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13417. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13418. glTextureFromLod.isCube = true;
  13419. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13424. if (loadData.isDDS) {
  13425. var info = loadData.info;
  13426. var data = loadData.data;
  13427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13428. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13429. }
  13430. else {
  13431. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13432. }
  13433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13434. // Wrap in a base texture for easy binding.
  13435. var lodTexture = new BABYLON.BaseTexture(scene);
  13436. lodTexture.isCube = true;
  13437. lodTexture._texture = glTextureFromLod;
  13438. glTextureFromLod.isReady = true;
  13439. textures.push(lodTexture);
  13440. }
  13441. texture._lodTextureHigh = textures[2];
  13442. texture._lodTextureMid = textures[1];
  13443. texture._lodTextureLow = textures[0];
  13444. if (onLoad) {
  13445. onLoad(texture);
  13446. }
  13447. };
  13448. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13449. };
  13450. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13451. var _this = this;
  13452. if (onLoad === void 0) { onLoad = null; }
  13453. if (onError === void 0) { onError = null; }
  13454. if (forcedExtension === void 0) { forcedExtension = null; }
  13455. var gl = this._gl;
  13456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13457. texture.isCube = true;
  13458. texture.url = rootUrl;
  13459. texture.generateMipMaps = !noMipmap;
  13460. if (!this._doNotHandleContextLost) {
  13461. texture._extension = forcedExtension;
  13462. texture._files = files;
  13463. }
  13464. var isKTX = false;
  13465. var isDDS = false;
  13466. var lastDot = rootUrl.lastIndexOf('.');
  13467. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13468. if (this._textureFormatInUse) {
  13469. extension = this._textureFormatInUse;
  13470. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13471. isKTX = true;
  13472. }
  13473. else {
  13474. isDDS = (extension === ".dds");
  13475. }
  13476. var onerror = function (request, exception) {
  13477. if (onError && request) {
  13478. onError(request.status + " " + request.statusText, exception);
  13479. }
  13480. };
  13481. if (isKTX) {
  13482. this._loadFile(rootUrl, function (data) {
  13483. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13484. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13485. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13486. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13487. ktx.uploadLevels(_this._gl, !noMipmap);
  13488. _this.setCubeMapTextureParams(gl, loadMipmap);
  13489. texture.width = ktx.pixelWidth;
  13490. texture.height = ktx.pixelHeight;
  13491. texture.isReady = true;
  13492. }, undefined, undefined, true, onerror);
  13493. }
  13494. else if (isDDS) {
  13495. if (files && files.length === 6) {
  13496. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13497. var info;
  13498. var loadMipmap = false;
  13499. var width = 0;
  13500. for (var index = 0; index < imgs.length; index++) {
  13501. var data = imgs[index];
  13502. info = BABYLON.DDSTools.GetDDSInfo(data);
  13503. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13504. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13505. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13506. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13507. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13508. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13509. }
  13510. texture.width = info.width;
  13511. texture.height = info.height;
  13512. texture.type = info.textureType;
  13513. width = info.width;
  13514. }
  13515. _this.setCubeMapTextureParams(gl, loadMipmap);
  13516. texture.isReady = true;
  13517. if (onLoad) {
  13518. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13519. }
  13520. }, files, onError);
  13521. }
  13522. else {
  13523. this._loadFile(rootUrl, function (data) {
  13524. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13525. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13526. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13527. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13528. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13529. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13530. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13531. }
  13532. _this.setCubeMapTextureParams(gl, loadMipmap);
  13533. texture.width = info.width;
  13534. texture.height = info.height;
  13535. texture.isReady = true;
  13536. texture.type = info.textureType;
  13537. if (onLoad) {
  13538. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13539. }
  13540. }, undefined, undefined, true, onerror);
  13541. }
  13542. }
  13543. else {
  13544. if (!files) {
  13545. throw new Error("Cannot load cubemap because files were not defined");
  13546. }
  13547. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13548. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13549. var height = width;
  13550. _this._prepareWorkingCanvas();
  13551. if (!_this._workingCanvas || !_this._workingContext) {
  13552. return;
  13553. }
  13554. _this._workingCanvas.width = width;
  13555. _this._workingCanvas.height = height;
  13556. var faces = [
  13557. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13558. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13559. ];
  13560. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13561. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13562. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13563. for (var index = 0; index < faces.length; index++) {
  13564. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13565. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13566. }
  13567. if (!noMipmap) {
  13568. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13569. }
  13570. _this.setCubeMapTextureParams(gl, !noMipmap);
  13571. texture.width = width;
  13572. texture.height = height;
  13573. texture.isReady = true;
  13574. if (format) {
  13575. texture.format = format;
  13576. }
  13577. texture.onLoadedObservable.notifyObservers(texture);
  13578. texture.onLoadedObservable.clear();
  13579. if (onLoad) {
  13580. onLoad();
  13581. }
  13582. }, files, onError);
  13583. }
  13584. this._internalTexturesCache.push(texture);
  13585. return texture;
  13586. };
  13587. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13592. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13593. // this.resetTextureCache();
  13594. };
  13595. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13596. if (compression === void 0) { compression = null; }
  13597. if (level === void 0) { level = 0; }
  13598. texture._bufferViewArray = data;
  13599. texture.format = format;
  13600. texture.type = type;
  13601. texture.invertY = invertY;
  13602. texture._compression = compression;
  13603. var gl = this._gl;
  13604. var textureType = this._getWebGLTextureType(type);
  13605. var internalFormat = this._getInternalFormat(format);
  13606. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13607. var needConversion = false;
  13608. if (internalFormat === gl.RGB) {
  13609. internalFormat = gl.RGBA;
  13610. needConversion = true;
  13611. }
  13612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13613. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13614. if (texture.width % 4 !== 0) {
  13615. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13616. }
  13617. // Data are known to be in +X +Y +Z -X -Y -Z
  13618. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13619. var faceData = data[faceIndex];
  13620. if (compression) {
  13621. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13622. }
  13623. else {
  13624. if (needConversion) {
  13625. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13626. }
  13627. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13628. }
  13629. }
  13630. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13631. if (isPot && texture.generateMipMaps && level === 0) {
  13632. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13633. }
  13634. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13635. // this.resetTextureCache();
  13636. texture.isReady = true;
  13637. };
  13638. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13639. if (compression === void 0) { compression = null; }
  13640. var gl = this._gl;
  13641. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13642. texture.isCube = true;
  13643. texture.generateMipMaps = generateMipMaps;
  13644. texture.format = format;
  13645. texture.type = type;
  13646. if (!this._doNotHandleContextLost) {
  13647. texture._bufferViewArray = data;
  13648. }
  13649. var textureType = this._getWebGLTextureType(type);
  13650. var internalFormat = this._getInternalFormat(format);
  13651. if (internalFormat === gl.RGB) {
  13652. internalFormat = gl.RGBA;
  13653. }
  13654. var width = size;
  13655. var height = width;
  13656. texture.width = width;
  13657. texture.height = height;
  13658. // Double check on POT to generate Mips.
  13659. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13660. if (!isPot) {
  13661. generateMipMaps = false;
  13662. }
  13663. // Upload data if needed. The texture won't be ready until then.
  13664. if (data) {
  13665. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13666. }
  13667. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13668. // Filters
  13669. if (data && generateMipMaps) {
  13670. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13671. }
  13672. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13675. }
  13676. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13679. }
  13680. else {
  13681. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13684. }
  13685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13688. return texture;
  13689. };
  13690. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13691. var _this = this;
  13692. if (onLoad === void 0) { onLoad = null; }
  13693. if (onError === void 0) { onError = null; }
  13694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13695. if (invertY === void 0) { invertY = false; }
  13696. var gl = this._gl;
  13697. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13698. scene._addPendingData(texture);
  13699. texture.url = url;
  13700. this._internalTexturesCache.push(texture);
  13701. var onerror = function (request, exception) {
  13702. scene._removePendingData(texture);
  13703. if (onError && request) {
  13704. onError(request.status + " " + request.statusText, exception);
  13705. }
  13706. };
  13707. var internalCallback = function (data) {
  13708. var width = texture.width;
  13709. var faceDataArrays = callback(data);
  13710. if (!faceDataArrays) {
  13711. return;
  13712. }
  13713. if (mipmmapGenerator) {
  13714. var textureType = _this._getWebGLTextureType(type);
  13715. var internalFormat = _this._getInternalFormat(format);
  13716. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13717. var needConversion = false;
  13718. if (internalFormat === gl.RGB) {
  13719. internalFormat = gl.RGBA;
  13720. needConversion = true;
  13721. }
  13722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13723. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13724. var mipData = mipmmapGenerator(faceDataArrays);
  13725. for (var level = 0; level < mipData.length; level++) {
  13726. var mipSize = width >> level;
  13727. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13728. var mipFaceData = mipData[level][faceIndex];
  13729. if (needConversion) {
  13730. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13731. }
  13732. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13733. }
  13734. }
  13735. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13736. }
  13737. else {
  13738. texture.generateMipMaps = !noMipmap;
  13739. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13740. }
  13741. texture.isReady = true;
  13742. // this.resetTextureCache();
  13743. scene._removePendingData(texture);
  13744. if (onLoad) {
  13745. onLoad();
  13746. }
  13747. };
  13748. this._loadFile(url, function (data) {
  13749. internalCallback(data);
  13750. }, undefined, scene.database, true, onerror);
  13751. return texture;
  13752. };
  13753. ;
  13754. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13755. if (compression === void 0) { compression = null; }
  13756. var internalFormat = this._getInternalFormat(format);
  13757. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13758. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13759. if (!this._doNotHandleContextLost) {
  13760. texture._bufferView = data;
  13761. texture.format = format;
  13762. texture.invertY = invertY;
  13763. texture._compression = compression;
  13764. }
  13765. if (texture.width % 4 !== 0) {
  13766. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13767. }
  13768. if (compression && data) {
  13769. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13770. }
  13771. else {
  13772. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13773. }
  13774. if (texture.generateMipMaps) {
  13775. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13776. }
  13777. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13778. // this.resetTextureCache();
  13779. texture.isReady = true;
  13780. };
  13781. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13782. if (compression === void 0) { compression = null; }
  13783. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13784. texture.baseWidth = width;
  13785. texture.baseHeight = height;
  13786. texture.baseDepth = depth;
  13787. texture.width = width;
  13788. texture.height = height;
  13789. texture.depth = depth;
  13790. texture.format = format;
  13791. texture.generateMipMaps = generateMipMaps;
  13792. texture.samplingMode = samplingMode;
  13793. texture.is3D = true;
  13794. if (!this._doNotHandleContextLost) {
  13795. texture._bufferView = data;
  13796. }
  13797. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13798. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13799. // Filters
  13800. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13803. if (generateMipMaps) {
  13804. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13805. }
  13806. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13807. this._internalTexturesCache.push(texture);
  13808. return texture;
  13809. };
  13810. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13811. var gl = this._gl;
  13812. if (!gl) {
  13813. return;
  13814. }
  13815. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13818. if (!noMipmap && !isCompressed) {
  13819. gl.generateMipmap(gl.TEXTURE_2D);
  13820. }
  13821. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13822. // this.resetTextureCache();
  13823. if (scene) {
  13824. scene._removePendingData(texture);
  13825. }
  13826. texture.onLoadedObservable.notifyObservers(texture);
  13827. texture.onLoadedObservable.clear();
  13828. };
  13829. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13830. var _this = this;
  13831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13832. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13833. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13834. var gl = this._gl;
  13835. if (!gl) {
  13836. return;
  13837. }
  13838. if (!texture._webGLTexture) {
  13839. // this.resetTextureCache();
  13840. if (scene) {
  13841. scene._removePendingData(texture);
  13842. }
  13843. return;
  13844. }
  13845. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13846. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13847. texture.baseWidth = width;
  13848. texture.baseHeight = height;
  13849. texture.width = potWidth;
  13850. texture.height = potHeight;
  13851. texture.isReady = true;
  13852. if (processFunction(potWidth, potHeight, function () {
  13853. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13854. })) {
  13855. // Returning as texture needs extra async steps
  13856. return;
  13857. }
  13858. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13859. };
  13860. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13861. // Create new RGBA data container.
  13862. var rgbaData;
  13863. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13864. rgbaData = new Float32Array(width * height * 4);
  13865. }
  13866. else {
  13867. rgbaData = new Uint32Array(width * height * 4);
  13868. }
  13869. // Convert each pixel.
  13870. for (var x = 0; x < width; x++) {
  13871. for (var y = 0; y < height; y++) {
  13872. var index = (y * width + x) * 3;
  13873. var newIndex = (y * width + x) * 4;
  13874. // Map Old Value to new value.
  13875. rgbaData[newIndex + 0] = rgbData[index + 0];
  13876. rgbaData[newIndex + 1] = rgbData[index + 1];
  13877. rgbaData[newIndex + 2] = rgbData[index + 2];
  13878. // Add fully opaque alpha channel.
  13879. rgbaData[newIndex + 3] = 1;
  13880. }
  13881. }
  13882. return rgbaData;
  13883. };
  13884. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13885. var gl = this._gl;
  13886. if (texture._framebuffer) {
  13887. gl.deleteFramebuffer(texture._framebuffer);
  13888. texture._framebuffer = null;
  13889. }
  13890. if (texture._depthStencilBuffer) {
  13891. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13892. texture._depthStencilBuffer = null;
  13893. }
  13894. if (texture._MSAAFramebuffer) {
  13895. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13896. texture._MSAAFramebuffer = null;
  13897. }
  13898. if (texture._MSAARenderBuffer) {
  13899. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13900. texture._MSAARenderBuffer = null;
  13901. }
  13902. };
  13903. Engine.prototype._releaseTexture = function (texture) {
  13904. var gl = this._gl;
  13905. this._releaseFramebufferObjects(texture);
  13906. gl.deleteTexture(texture._webGLTexture);
  13907. // Unbind channels
  13908. this.unbindAllTextures();
  13909. var index = this._internalTexturesCache.indexOf(texture);
  13910. if (index !== -1) {
  13911. this._internalTexturesCache.splice(index, 1);
  13912. }
  13913. // Integrated fixed lod samplers.
  13914. if (texture._lodTextureHigh) {
  13915. texture._lodTextureHigh.dispose();
  13916. }
  13917. if (texture._lodTextureMid) {
  13918. texture._lodTextureMid.dispose();
  13919. }
  13920. if (texture._lodTextureLow) {
  13921. texture._lodTextureLow.dispose();
  13922. }
  13923. };
  13924. Engine.prototype.setProgram = function (program) {
  13925. if (this._currentProgram !== program) {
  13926. this._gl.useProgram(program);
  13927. this._currentProgram = program;
  13928. }
  13929. };
  13930. Engine.prototype.bindSamplers = function (effect) {
  13931. this.setProgram(effect.getProgram());
  13932. var samplers = effect.getSamplers();
  13933. for (var index = 0; index < samplers.length; index++) {
  13934. var uniform = effect.getUniform(samplers[index]);
  13935. if (uniform) {
  13936. this._boundUniforms[index] = uniform;
  13937. }
  13938. }
  13939. this._currentEffect = null;
  13940. };
  13941. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13942. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13943. return;
  13944. }
  13945. // Remove
  13946. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13947. // Bind last to it
  13948. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13949. // Bind to dummy
  13950. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13951. };
  13952. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13953. if (!internalTexture) {
  13954. return -1;
  13955. }
  13956. internalTexture._initialSlot = channel;
  13957. if (this.disableTextureBindingOptimization) {
  13958. if (channel !== internalTexture._designatedSlot) {
  13959. this._textureCollisions.addCount(1, false);
  13960. }
  13961. }
  13962. else {
  13963. if (channel !== internalTexture._designatedSlot) {
  13964. if (internalTexture._designatedSlot > -1) {
  13965. return internalTexture._designatedSlot;
  13966. }
  13967. else {
  13968. // No slot for this texture, let's pick a new one (if we find a free slot)
  13969. if (this._nextFreeTextureSlots.length) {
  13970. return this._nextFreeTextureSlots[0];
  13971. }
  13972. // We need to recycle the oldest bound texture, sorry.
  13973. this._textureCollisions.addCount(1, false);
  13974. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13975. }
  13976. }
  13977. }
  13978. return channel;
  13979. };
  13980. Engine.prototype._linkTrackers = function (previous, next) {
  13981. previous.next = next;
  13982. next.previous = previous;
  13983. };
  13984. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13985. var currentSlot = internalTexture._designatedSlot;
  13986. if (currentSlot === -1) {
  13987. return -1;
  13988. }
  13989. internalTexture._designatedSlot = -1;
  13990. if (this.disableTextureBindingOptimization) {
  13991. return -1;
  13992. }
  13993. // Remove from bound list
  13994. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13995. // Free the slot
  13996. this._boundTexturesCache[currentSlot] = null;
  13997. this._nextFreeTextureSlots.push(currentSlot);
  13998. return currentSlot;
  13999. };
  14000. Engine.prototype._activateCurrentTexture = function () {
  14001. if (this._currentTextureChannel !== this._activeChannel) {
  14002. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14003. this._currentTextureChannel = this._activeChannel;
  14004. }
  14005. };
  14006. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14007. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14008. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14009. this._activeChannel = texture._designatedSlot;
  14010. }
  14011. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14012. var isTextureForRendering = texture && texture._initialSlot > -1;
  14013. if (currentTextureBound !== texture) {
  14014. if (currentTextureBound) {
  14015. this._removeDesignatedSlot(currentTextureBound);
  14016. }
  14017. this._activateCurrentTexture();
  14018. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14019. this._boundTexturesCache[this._activeChannel] = texture;
  14020. if (texture) {
  14021. if (!this.disableTextureBindingOptimization) {
  14022. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14023. if (slotIndex > -1) {
  14024. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14025. }
  14026. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14027. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14028. }
  14029. texture._designatedSlot = this._activeChannel;
  14030. }
  14031. }
  14032. else if (forTextureDataUpdate) {
  14033. this._activateCurrentTexture();
  14034. }
  14035. if (isTextureForRendering && !forTextureDataUpdate) {
  14036. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14037. }
  14038. };
  14039. Engine.prototype._bindTexture = function (channel, texture) {
  14040. if (channel < 0) {
  14041. return;
  14042. }
  14043. if (texture) {
  14044. channel = this._getCorrectTextureChannel(channel, texture);
  14045. }
  14046. this._activeChannel = channel;
  14047. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14048. };
  14049. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14050. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14051. };
  14052. Engine.prototype.unbindAllTextures = function () {
  14053. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14054. this._activeChannel = channel;
  14055. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14057. if (this.webGLVersion > 1) {
  14058. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14059. }
  14060. }
  14061. };
  14062. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14063. if (channel < 0) {
  14064. return;
  14065. }
  14066. if (uniform) {
  14067. this._boundUniforms[channel] = uniform;
  14068. }
  14069. this._setTexture(channel, texture);
  14070. };
  14071. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14072. var uniform = this._boundUniforms[sourceSlot];
  14073. if (uniform._currentState === destination) {
  14074. return;
  14075. }
  14076. this._gl.uniform1i(uniform, destination);
  14077. uniform._currentState = destination;
  14078. };
  14079. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14080. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14081. // Not ready?
  14082. if (!texture) {
  14083. if (this._boundTexturesCache[channel] != null) {
  14084. this._activeChannel = channel;
  14085. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14086. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14087. if (this.webGLVersion > 1) {
  14088. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14089. }
  14090. }
  14091. return false;
  14092. }
  14093. // Video
  14094. if (texture.video) {
  14095. this._activeChannel = channel;
  14096. texture.update();
  14097. }
  14098. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14099. texture.delayLoad();
  14100. return false;
  14101. }
  14102. var internalTexture;
  14103. if (texture.isReady()) {
  14104. internalTexture = texture.getInternalTexture();
  14105. }
  14106. else if (texture.isCube) {
  14107. internalTexture = this.emptyCubeTexture;
  14108. }
  14109. else if (texture.is3D) {
  14110. internalTexture = this.emptyTexture3D;
  14111. }
  14112. else {
  14113. internalTexture = this.emptyTexture;
  14114. }
  14115. if (!isPartOfTextureArray) {
  14116. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14117. }
  14118. if (this._boundTexturesCache[channel] === internalTexture) {
  14119. this._moveBoundTextureOnTop(internalTexture);
  14120. if (!isPartOfTextureArray) {
  14121. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14122. }
  14123. return false;
  14124. }
  14125. this._activeChannel = channel;
  14126. if (internalTexture && internalTexture.is3D) {
  14127. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14128. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14129. internalTexture._cachedWrapU = texture.wrapU;
  14130. switch (texture.wrapU) {
  14131. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14132. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14133. break;
  14134. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14135. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14136. break;
  14137. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14138. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14139. break;
  14140. }
  14141. }
  14142. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14143. internalTexture._cachedWrapV = texture.wrapV;
  14144. switch (texture.wrapV) {
  14145. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14146. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14147. break;
  14148. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14150. break;
  14151. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14152. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14153. break;
  14154. }
  14155. }
  14156. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14157. internalTexture._cachedWrapR = texture.wrapR;
  14158. switch (texture.wrapR) {
  14159. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14160. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14161. break;
  14162. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14164. break;
  14165. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14166. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14167. break;
  14168. }
  14169. }
  14170. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14171. }
  14172. else if (internalTexture && internalTexture.isCube) {
  14173. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14174. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14175. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14176. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14177. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14178. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14179. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14180. }
  14181. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14182. }
  14183. else {
  14184. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14185. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14186. internalTexture._cachedWrapU = texture.wrapU;
  14187. switch (texture.wrapU) {
  14188. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14189. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14190. break;
  14191. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14193. break;
  14194. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14195. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14196. break;
  14197. }
  14198. }
  14199. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14200. internalTexture._cachedWrapV = texture.wrapV;
  14201. switch (texture.wrapV) {
  14202. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14204. break;
  14205. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14207. break;
  14208. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14210. break;
  14211. }
  14212. }
  14213. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14214. }
  14215. return true;
  14216. };
  14217. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14218. if (channel < 0 || !uniform) {
  14219. return;
  14220. }
  14221. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14222. this._textureUnits = new Int32Array(textures.length);
  14223. }
  14224. for (var i = 0; i < textures.length; i++) {
  14225. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14226. }
  14227. this._gl.uniform1iv(uniform, this._textureUnits);
  14228. for (var index = 0; index < textures.length; index++) {
  14229. this._setTexture(this._textureUnits[index], textures[index], true);
  14230. }
  14231. };
  14232. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14233. var internalTexture = texture.getInternalTexture();
  14234. if (!internalTexture) {
  14235. return;
  14236. }
  14237. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14238. var value = texture.anisotropicFilteringLevel;
  14239. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14240. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14241. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14242. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14243. }
  14244. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14245. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14246. internalTexture._cachedAnisotropicFilteringLevel = value;
  14247. }
  14248. };
  14249. Engine.prototype.readPixels = function (x, y, width, height) {
  14250. var data = new Uint8Array(height * width * 4);
  14251. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14252. return data;
  14253. };
  14254. /**
  14255. * Add an externaly attached data from its key.
  14256. * This method call will fail and return false, if such key already exists.
  14257. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14258. * @param key the unique key that identifies the data
  14259. * @param data the data object to associate to the key for this Engine instance
  14260. * @return true if no such key were already present and the data was added successfully, false otherwise
  14261. */
  14262. Engine.prototype.addExternalData = function (key, data) {
  14263. if (!this._externalData) {
  14264. this._externalData = new BABYLON.StringDictionary();
  14265. }
  14266. return this._externalData.add(key, data);
  14267. };
  14268. /**
  14269. * Get an externaly attached data from its key
  14270. * @param key the unique key that identifies the data
  14271. * @return the associated data, if present (can be null), or undefined if not present
  14272. */
  14273. Engine.prototype.getExternalData = function (key) {
  14274. if (!this._externalData) {
  14275. this._externalData = new BABYLON.StringDictionary();
  14276. }
  14277. return this._externalData.get(key);
  14278. };
  14279. /**
  14280. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14281. * @param key the unique key that identifies the data
  14282. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14283. * @return the associated data, can be null if the factory returned null.
  14284. */
  14285. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14286. if (!this._externalData) {
  14287. this._externalData = new BABYLON.StringDictionary();
  14288. }
  14289. return this._externalData.getOrAddWithFactory(key, factory);
  14290. };
  14291. /**
  14292. * Remove an externaly attached data from the Engine instance
  14293. * @param key the unique key that identifies the data
  14294. * @return true if the data was successfully removed, false if it doesn't exist
  14295. */
  14296. Engine.prototype.removeExternalData = function (key) {
  14297. if (!this._externalData) {
  14298. this._externalData = new BABYLON.StringDictionary();
  14299. }
  14300. return this._externalData.remove(key);
  14301. };
  14302. Engine.prototype.unbindAllAttributes = function () {
  14303. if (this._mustWipeVertexAttributes) {
  14304. this._mustWipeVertexAttributes = false;
  14305. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14306. this._gl.disableVertexAttribArray(i);
  14307. this._vertexAttribArraysEnabled[i] = false;
  14308. this._currentBufferPointers[i].active = false;
  14309. }
  14310. return;
  14311. }
  14312. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14313. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14314. continue;
  14315. }
  14316. this._gl.disableVertexAttribArray(i);
  14317. this._vertexAttribArraysEnabled[i] = false;
  14318. this._currentBufferPointers[i].active = false;
  14319. }
  14320. };
  14321. Engine.prototype.releaseEffects = function () {
  14322. for (var name in this._compiledEffects) {
  14323. this._deleteProgram(this._compiledEffects[name]._program);
  14324. }
  14325. this._compiledEffects = {};
  14326. };
  14327. // Dispose
  14328. Engine.prototype.dispose = function () {
  14329. this.hideLoadingUI();
  14330. this.stopRenderLoop();
  14331. // Release postProcesses
  14332. while (this.postProcesses.length) {
  14333. this.postProcesses[0].dispose();
  14334. }
  14335. // Empty texture
  14336. if (this._emptyTexture) {
  14337. this._releaseTexture(this._emptyTexture);
  14338. this._emptyTexture = null;
  14339. }
  14340. if (this._emptyCubeTexture) {
  14341. this._releaseTexture(this._emptyCubeTexture);
  14342. this._emptyCubeTexture = null;
  14343. }
  14344. // Rescale PP
  14345. if (this._rescalePostProcess) {
  14346. this._rescalePostProcess.dispose();
  14347. }
  14348. // Release scenes
  14349. while (this.scenes.length) {
  14350. this.scenes[0].dispose();
  14351. }
  14352. // Release audio engine
  14353. if (Engine.audioEngine) {
  14354. Engine.audioEngine.dispose();
  14355. }
  14356. // Release effects
  14357. this.releaseEffects();
  14358. // Unbind
  14359. this.unbindAllAttributes();
  14360. if (this._dummyFramebuffer) {
  14361. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14362. }
  14363. //WebVR
  14364. this.disableVR();
  14365. // Events
  14366. if (BABYLON.Tools.IsWindowObjectExist()) {
  14367. window.removeEventListener("blur", this._onBlur);
  14368. window.removeEventListener("focus", this._onFocus);
  14369. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14370. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14371. if (this._renderingCanvas) {
  14372. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14373. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14374. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14375. if (!this._doNotHandleContextLost) {
  14376. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14377. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14378. }
  14379. }
  14380. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14381. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14382. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14383. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14384. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14385. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14386. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14387. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14388. if (this._onVrDisplayConnect) {
  14389. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14390. if (this._onVrDisplayDisconnect) {
  14391. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14392. }
  14393. if (this._onVrDisplayPresentChange) {
  14394. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14395. }
  14396. this._onVrDisplayConnect = null;
  14397. this._onVrDisplayDisconnect = null;
  14398. }
  14399. }
  14400. // Remove from Instances
  14401. var index = Engine.Instances.indexOf(this);
  14402. if (index >= 0) {
  14403. Engine.Instances.splice(index, 1);
  14404. }
  14405. this._workingCanvas = null;
  14406. this._workingContext = null;
  14407. this._currentBufferPointers = [];
  14408. this._renderingCanvas = null;
  14409. this._currentProgram = null;
  14410. this.onResizeObservable.clear();
  14411. this.onCanvasBlurObservable.clear();
  14412. this.onCanvasFocusObservable.clear();
  14413. this.onCanvasPointerOutObservable.clear();
  14414. this.onBeginFrameObservable.clear();
  14415. this.onEndFrameObservable.clear();
  14416. BABYLON.Effect.ResetCache();
  14417. // Abort active requests
  14418. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14419. var request = _a[_i];
  14420. request.abort();
  14421. }
  14422. };
  14423. // Loading screen
  14424. Engine.prototype.displayLoadingUI = function () {
  14425. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14426. return;
  14427. }
  14428. var loadingScreen = this.loadingScreen;
  14429. if (loadingScreen) {
  14430. loadingScreen.displayLoadingUI();
  14431. }
  14432. };
  14433. Engine.prototype.hideLoadingUI = function () {
  14434. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14435. return;
  14436. }
  14437. var loadingScreen = this.loadingScreen;
  14438. if (loadingScreen) {
  14439. loadingScreen.hideLoadingUI();
  14440. }
  14441. };
  14442. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14443. get: function () {
  14444. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14445. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14446. return this._loadingScreen;
  14447. },
  14448. set: function (loadingScreen) {
  14449. this._loadingScreen = loadingScreen;
  14450. },
  14451. enumerable: true,
  14452. configurable: true
  14453. });
  14454. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14455. set: function (text) {
  14456. this.loadingScreen.loadingUIText = text;
  14457. },
  14458. enumerable: true,
  14459. configurable: true
  14460. });
  14461. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14462. set: function (color) {
  14463. this.loadingScreen.loadingUIBackgroundColor = color;
  14464. },
  14465. enumerable: true,
  14466. configurable: true
  14467. });
  14468. Engine.prototype.attachContextLostEvent = function (callback) {
  14469. if (this._renderingCanvas) {
  14470. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14471. }
  14472. };
  14473. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14474. if (this._renderingCanvas) {
  14475. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14476. }
  14477. };
  14478. Engine.prototype.getVertexShaderSource = function (program) {
  14479. var shaders = this._gl.getAttachedShaders(program);
  14480. if (!shaders) {
  14481. return null;
  14482. }
  14483. return this._gl.getShaderSource(shaders[0]);
  14484. };
  14485. Engine.prototype.getFragmentShaderSource = function (program) {
  14486. var shaders = this._gl.getAttachedShaders(program);
  14487. if (!shaders) {
  14488. return null;
  14489. }
  14490. return this._gl.getShaderSource(shaders[1]);
  14491. };
  14492. Engine.prototype.getError = function () {
  14493. return this._gl.getError();
  14494. };
  14495. // FPS
  14496. Engine.prototype.getFps = function () {
  14497. return this._fps;
  14498. };
  14499. Engine.prototype.getDeltaTime = function () {
  14500. return this._deltaTime;
  14501. };
  14502. Engine.prototype._measureFps = function () {
  14503. this._performanceMonitor.sampleFrame();
  14504. this._fps = this._performanceMonitor.averageFPS;
  14505. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14506. };
  14507. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14508. if (faceIndex === void 0) { faceIndex = -1; }
  14509. var gl = this._gl;
  14510. if (!this._dummyFramebuffer) {
  14511. var dummy = gl.createFramebuffer();
  14512. if (!dummy) {
  14513. throw new Error("Unable to create dummy framebuffer");
  14514. }
  14515. this._dummyFramebuffer = dummy;
  14516. }
  14517. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14518. if (faceIndex > -1) {
  14519. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14520. }
  14521. else {
  14522. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14523. }
  14524. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14525. var buffer;
  14526. switch (readType) {
  14527. case gl.UNSIGNED_BYTE:
  14528. buffer = new Uint8Array(4 * width * height);
  14529. readType = gl.UNSIGNED_BYTE;
  14530. break;
  14531. default:
  14532. buffer = new Float32Array(4 * width * height);
  14533. readType = gl.FLOAT;
  14534. break;
  14535. }
  14536. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14537. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14538. return buffer;
  14539. };
  14540. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14541. if (this._webGLVersion > 1) {
  14542. return this._caps.colorBufferFloat;
  14543. }
  14544. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14545. };
  14546. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14547. if (this._webGLVersion > 1) {
  14548. return this._caps.colorBufferFloat;
  14549. }
  14550. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14551. };
  14552. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14553. Engine.prototype._canRenderToFramebuffer = function (type) {
  14554. var gl = this._gl;
  14555. //clear existing errors
  14556. while (gl.getError() !== gl.NO_ERROR) { }
  14557. var successful = true;
  14558. var texture = gl.createTexture();
  14559. gl.bindTexture(gl.TEXTURE_2D, texture);
  14560. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14563. var fb = gl.createFramebuffer();
  14564. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14565. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14566. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14567. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14568. successful = successful && (gl.getError() === gl.NO_ERROR);
  14569. //try render by clearing frame buffer's color buffer
  14570. if (successful) {
  14571. gl.clear(gl.COLOR_BUFFER_BIT);
  14572. successful = successful && (gl.getError() === gl.NO_ERROR);
  14573. }
  14574. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14575. if (successful) {
  14576. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14577. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14578. var readFormat = gl.RGBA;
  14579. var readType = gl.UNSIGNED_BYTE;
  14580. var buffer = new Uint8Array(4);
  14581. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14582. successful = successful && (gl.getError() === gl.NO_ERROR);
  14583. }
  14584. //clean up
  14585. gl.deleteTexture(texture);
  14586. gl.deleteFramebuffer(fb);
  14587. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14588. //clear accumulated errors
  14589. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14590. return successful;
  14591. };
  14592. Engine.prototype._getWebGLTextureType = function (type) {
  14593. if (type === Engine.TEXTURETYPE_FLOAT) {
  14594. return this._gl.FLOAT;
  14595. }
  14596. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14597. // Add Half Float Constant.
  14598. return this._gl.HALF_FLOAT_OES;
  14599. }
  14600. return this._gl.UNSIGNED_BYTE;
  14601. };
  14602. ;
  14603. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14604. if (this._webGLVersion === 1) {
  14605. return this._gl.RGBA;
  14606. }
  14607. if (type === Engine.TEXTURETYPE_FLOAT) {
  14608. return this._gl.RGBA32F;
  14609. }
  14610. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14611. return this._gl.RGBA16F;
  14612. }
  14613. return this._gl.RGBA;
  14614. };
  14615. ;
  14616. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14617. if (type === Engine.TEXTURETYPE_FLOAT) {
  14618. return this._gl.RGBA32F;
  14619. }
  14620. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14621. return this._gl.RGBA16F;
  14622. }
  14623. return this._gl.RGBA8;
  14624. };
  14625. ;
  14626. Engine.prototype.createQuery = function () {
  14627. return this._gl.createQuery();
  14628. };
  14629. Engine.prototype.deleteQuery = function (query) {
  14630. this._gl.deleteQuery(query);
  14631. return this;
  14632. };
  14633. Engine.prototype.isQueryResultAvailable = function (query) {
  14634. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14635. };
  14636. Engine.prototype.getQueryResult = function (query) {
  14637. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14638. };
  14639. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14640. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14641. this._gl.beginQuery(glAlgorithm, query);
  14642. return this;
  14643. };
  14644. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14645. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14646. this._gl.endQuery(glAlgorithm);
  14647. return this;
  14648. };
  14649. /* Time queries */
  14650. Engine.prototype._createTimeQuery = function () {
  14651. var timerQuery = this._caps.timerQuery;
  14652. if (timerQuery.createQueryEXT) {
  14653. return timerQuery.createQueryEXT();
  14654. }
  14655. return this.createQuery();
  14656. };
  14657. Engine.prototype._deleteTimeQuery = function (query) {
  14658. var timerQuery = this._caps.timerQuery;
  14659. if (timerQuery.deleteQueryEXT) {
  14660. timerQuery.deleteQueryEXT(query);
  14661. return;
  14662. }
  14663. this.deleteQuery(query);
  14664. };
  14665. Engine.prototype._getTimeQueryResult = function (query) {
  14666. var timerQuery = this._caps.timerQuery;
  14667. if (timerQuery.getQueryObjectEXT) {
  14668. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14669. }
  14670. return this.getQueryResult(query);
  14671. };
  14672. Engine.prototype._getTimeQueryAvailability = function (query) {
  14673. var timerQuery = this._caps.timerQuery;
  14674. if (timerQuery.getQueryObjectEXT) {
  14675. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14676. }
  14677. return this.isQueryResultAvailable(query);
  14678. };
  14679. Engine.prototype.startTimeQuery = function () {
  14680. var timerQuery = this._caps.timerQuery;
  14681. if (!timerQuery) {
  14682. return null;
  14683. }
  14684. var token = new BABYLON._TimeToken();
  14685. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14686. if (this._caps.canUseTimestampForTimerQuery) {
  14687. token._startTimeQuery = this._createTimeQuery();
  14688. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14689. }
  14690. else {
  14691. if (this._currentNonTimestampToken) {
  14692. return this._currentNonTimestampToken;
  14693. }
  14694. token._timeElapsedQuery = this._createTimeQuery();
  14695. if (timerQuery.beginQueryEXT) {
  14696. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14697. }
  14698. else {
  14699. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14700. }
  14701. this._currentNonTimestampToken = token;
  14702. }
  14703. return token;
  14704. };
  14705. Engine.prototype.endTimeQuery = function (token) {
  14706. var timerQuery = this._caps.timerQuery;
  14707. if (!timerQuery || !token) {
  14708. return -1;
  14709. }
  14710. if (this._caps.canUseTimestampForTimerQuery) {
  14711. if (!token._startTimeQuery) {
  14712. return -1;
  14713. }
  14714. if (!token._endTimeQuery) {
  14715. token._endTimeQuery = this._createTimeQuery();
  14716. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14717. }
  14718. }
  14719. else if (!token._timeElapsedQueryEnded) {
  14720. if (!token._timeElapsedQuery) {
  14721. return -1;
  14722. }
  14723. if (timerQuery.endQueryEXT) {
  14724. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14725. }
  14726. else {
  14727. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14728. }
  14729. token._timeElapsedQueryEnded = true;
  14730. }
  14731. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14732. var available = false;
  14733. if (token._endTimeQuery) {
  14734. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14735. }
  14736. else if (token._timeElapsedQuery) {
  14737. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14738. }
  14739. if (available && !disjoint) {
  14740. var result = 0;
  14741. if (this._caps.canUseTimestampForTimerQuery) {
  14742. if (!token._startTimeQuery || !token._endTimeQuery) {
  14743. return -1;
  14744. }
  14745. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14746. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14747. result = timeEnd - timeStart;
  14748. this._deleteTimeQuery(token._startTimeQuery);
  14749. this._deleteTimeQuery(token._endTimeQuery);
  14750. token._startTimeQuery = null;
  14751. token._endTimeQuery = null;
  14752. }
  14753. else {
  14754. if (!token._timeElapsedQuery) {
  14755. return -1;
  14756. }
  14757. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14758. this._deleteTimeQuery(token._timeElapsedQuery);
  14759. token._timeElapsedQuery = null;
  14760. token._timeElapsedQueryEnded = false;
  14761. this._currentNonTimestampToken = null;
  14762. }
  14763. return result;
  14764. }
  14765. return -1;
  14766. };
  14767. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14768. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14769. };
  14770. // Transform feedback
  14771. Engine.prototype.createTransformFeedback = function () {
  14772. return this._gl.createTransformFeedback();
  14773. };
  14774. Engine.prototype.deleteTransformFeedback = function (value) {
  14775. this._gl.deleteTransformFeedback(value);
  14776. };
  14777. Engine.prototype.bindTransformFeedback = function (value) {
  14778. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14779. };
  14780. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14781. if (usePoints === void 0) { usePoints = true; }
  14782. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14783. };
  14784. Engine.prototype.endTransformFeedback = function () {
  14785. this._gl.endTransformFeedback();
  14786. };
  14787. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14788. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14789. };
  14790. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14791. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14792. };
  14793. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14794. var _this = this;
  14795. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14796. this._activeRequests.push(request);
  14797. request.onCompleteObservable.add(function (request) {
  14798. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14799. });
  14800. return request;
  14801. };
  14802. /** @ignore */
  14803. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14804. var _this = this;
  14805. return new Promise(function (resolve, reject) {
  14806. _this._loadFile(url, function (data) {
  14807. resolve(data);
  14808. }, undefined, database, useArrayBuffer, function (request, exception) {
  14809. reject(exception);
  14810. });
  14811. });
  14812. };
  14813. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14814. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14815. var onload = function (data) {
  14816. loadedFiles[index] = data;
  14817. loadedFiles._internalCount++;
  14818. if (loadedFiles._internalCount === 6) {
  14819. onfinish(loadedFiles);
  14820. }
  14821. };
  14822. var onerror = function (request, exception) {
  14823. if (onErrorCallBack && request) {
  14824. onErrorCallBack(request.status + " " + request.statusText, exception);
  14825. }
  14826. };
  14827. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14828. };
  14829. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14830. if (onError === void 0) { onError = null; }
  14831. var loadedFiles = [];
  14832. loadedFiles._internalCount = 0;
  14833. for (var index = 0; index < 6; index++) {
  14834. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14835. }
  14836. };
  14837. // Statics
  14838. Engine.isSupported = function () {
  14839. try {
  14840. var tempcanvas = document.createElement("canvas");
  14841. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14842. return gl != null && !!window.WebGLRenderingContext;
  14843. }
  14844. catch (e) {
  14845. return false;
  14846. }
  14847. };
  14848. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14849. Engine.ExceptionList = [
  14850. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14851. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14852. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14853. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14854. ];
  14855. Engine.Instances = new Array();
  14856. // Const statics
  14857. Engine._ALPHA_DISABLE = 0;
  14858. Engine._ALPHA_ADD = 1;
  14859. Engine._ALPHA_COMBINE = 2;
  14860. Engine._ALPHA_SUBTRACT = 3;
  14861. Engine._ALPHA_MULTIPLY = 4;
  14862. Engine._ALPHA_MAXIMIZED = 5;
  14863. Engine._ALPHA_ONEONE = 6;
  14864. Engine._ALPHA_PREMULTIPLIED = 7;
  14865. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14866. Engine._ALPHA_INTERPOLATE = 9;
  14867. Engine._ALPHA_SCREENMODE = 10;
  14868. Engine._DELAYLOADSTATE_NONE = 0;
  14869. Engine._DELAYLOADSTATE_LOADED = 1;
  14870. Engine._DELAYLOADSTATE_LOADING = 2;
  14871. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14872. Engine._TEXTUREFORMAT_ALPHA = 0;
  14873. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14874. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14875. Engine._TEXTUREFORMAT_RGB = 4;
  14876. Engine._TEXTUREFORMAT_RGBA = 5;
  14877. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14878. Engine._TEXTURETYPE_FLOAT = 1;
  14879. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14880. // Depht or Stencil test Constants.
  14881. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14882. 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.
  14883. 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.
  14884. 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.
  14885. 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.
  14886. 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.
  14887. 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.
  14888. 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.
  14889. // Stencil Actions Constants.
  14890. Engine._KEEP = 0x1E00;
  14891. Engine._REPLACE = 0x1E01;
  14892. Engine._INCR = 0x1E02;
  14893. Engine._DECR = 0x1E03;
  14894. Engine._INVERT = 0x150A;
  14895. Engine._INCR_WRAP = 0x8507;
  14896. Engine._DECR_WRAP = 0x8508;
  14897. // Texture rescaling mode
  14898. Engine._SCALEMODE_FLOOR = 1;
  14899. Engine._SCALEMODE_NEAREST = 2;
  14900. Engine._SCALEMODE_CEILING = 3;
  14901. // Updatable statics so stick with vars here
  14902. Engine.CollisionsEpsilon = 0.001;
  14903. Engine.CodeRepository = "src/";
  14904. Engine.ShadersRepository = "src/Shaders/";
  14905. return Engine;
  14906. }());
  14907. BABYLON.Engine = Engine;
  14908. })(BABYLON || (BABYLON = {}));
  14909. //# sourceMappingURL=babylon.engine.js.map
  14910. var BABYLON;
  14911. (function (BABYLON) {
  14912. /**
  14913. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14914. */
  14915. var Node = /** @class */ (function () {
  14916. /**
  14917. * @constructor
  14918. * @param {string} name - the name and id to be given to this node
  14919. * @param {BABYLON.Scene} the scene this node will be added to
  14920. */
  14921. function Node(name, scene) {
  14922. if (scene === void 0) { scene = null; }
  14923. this.state = "";
  14924. this.metadata = null;
  14925. this.doNotSerialize = false;
  14926. this.animations = new Array();
  14927. this._ranges = {};
  14928. this._isEnabled = true;
  14929. this._isReady = true;
  14930. this._currentRenderId = -1;
  14931. this._parentRenderId = -1;
  14932. /**
  14933. * An event triggered when the mesh is disposed.
  14934. * @type {BABYLON.Observable}
  14935. */
  14936. this.onDisposeObservable = new BABYLON.Observable();
  14937. // Behaviors
  14938. this._behaviors = new Array();
  14939. this.name = name;
  14940. this.id = name;
  14941. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14942. this.uniqueId = this._scene.getUniqueId();
  14943. this._initCache();
  14944. }
  14945. Object.defineProperty(Node.prototype, "parent", {
  14946. get: function () {
  14947. return this._parentNode;
  14948. },
  14949. set: function (parent) {
  14950. if (this._parentNode === parent) {
  14951. return;
  14952. }
  14953. // Remove self from list of children of parent
  14954. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14955. var index = this._parentNode._children.indexOf(this);
  14956. if (index !== -1) {
  14957. this._parentNode._children.splice(index, 1);
  14958. }
  14959. }
  14960. // Store new parent
  14961. this._parentNode = parent;
  14962. // Add as child to new parent
  14963. if (this._parentNode) {
  14964. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14965. this._parentNode._children = new Array();
  14966. }
  14967. this._parentNode._children.push(this);
  14968. }
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Node.prototype.getClassName = function () {
  14974. return "Node";
  14975. };
  14976. Object.defineProperty(Node.prototype, "onDispose", {
  14977. set: function (callback) {
  14978. if (this._onDisposeObserver) {
  14979. this.onDisposeObservable.remove(this._onDisposeObserver);
  14980. }
  14981. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Node.prototype.getScene = function () {
  14987. return this._scene;
  14988. };
  14989. Node.prototype.getEngine = function () {
  14990. return this._scene.getEngine();
  14991. };
  14992. Node.prototype.addBehavior = function (behavior) {
  14993. var _this = this;
  14994. var index = this._behaviors.indexOf(behavior);
  14995. if (index !== -1) {
  14996. return this;
  14997. }
  14998. behavior.init();
  14999. if (this._scene.isLoading) {
  15000. // We defer the attach when the scene will be loaded
  15001. var observer = this._scene.onDataLoadedObservable.add(function () {
  15002. behavior.attach(_this);
  15003. setTimeout(function () {
  15004. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15005. _this._scene.onDataLoadedObservable.remove(observer);
  15006. }, 0);
  15007. });
  15008. }
  15009. else {
  15010. behavior.attach(this);
  15011. }
  15012. this._behaviors.push(behavior);
  15013. return this;
  15014. };
  15015. Node.prototype.removeBehavior = function (behavior) {
  15016. var index = this._behaviors.indexOf(behavior);
  15017. if (index === -1) {
  15018. return this;
  15019. }
  15020. this._behaviors[index].detach();
  15021. this._behaviors.splice(index, 1);
  15022. return this;
  15023. };
  15024. Object.defineProperty(Node.prototype, "behaviors", {
  15025. get: function () {
  15026. return this._behaviors;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. Node.prototype.getBehaviorByName = function (name) {
  15032. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15033. var behavior = _a[_i];
  15034. if (behavior.name === name) {
  15035. return behavior;
  15036. }
  15037. }
  15038. return null;
  15039. };
  15040. // override it in derived class
  15041. Node.prototype.getWorldMatrix = function () {
  15042. return BABYLON.Matrix.Identity();
  15043. };
  15044. // override it in derived class if you add new variables to the cache
  15045. // and call the parent class method
  15046. Node.prototype._initCache = function () {
  15047. this._cache = {};
  15048. this._cache.parent = undefined;
  15049. };
  15050. Node.prototype.updateCache = function (force) {
  15051. if (!force && this.isSynchronized())
  15052. return;
  15053. this._cache.parent = this.parent;
  15054. this._updateCache();
  15055. };
  15056. // override it in derived class if you add new variables to the cache
  15057. // and call the parent class method if !ignoreParentClass
  15058. Node.prototype._updateCache = function (ignoreParentClass) {
  15059. };
  15060. // override it in derived class if you add new variables to the cache
  15061. Node.prototype._isSynchronized = function () {
  15062. return true;
  15063. };
  15064. Node.prototype._markSyncedWithParent = function () {
  15065. if (this.parent) {
  15066. this._parentRenderId = this.parent._currentRenderId;
  15067. }
  15068. };
  15069. Node.prototype.isSynchronizedWithParent = function () {
  15070. if (!this.parent) {
  15071. return true;
  15072. }
  15073. if (this._parentRenderId !== this.parent._currentRenderId) {
  15074. return false;
  15075. }
  15076. return this.parent.isSynchronized();
  15077. };
  15078. Node.prototype.isSynchronized = function (updateCache) {
  15079. var check = this.hasNewParent();
  15080. check = check || !this.isSynchronizedWithParent();
  15081. check = check || !this._isSynchronized();
  15082. if (updateCache)
  15083. this.updateCache(true);
  15084. return !check;
  15085. };
  15086. Node.prototype.hasNewParent = function (update) {
  15087. if (this._cache.parent === this.parent)
  15088. return false;
  15089. if (update)
  15090. this._cache.parent = this.parent;
  15091. return true;
  15092. };
  15093. /**
  15094. * Is this node ready to be used/rendered
  15095. * @return {boolean} is it ready
  15096. */
  15097. Node.prototype.isReady = function () {
  15098. return this._isReady;
  15099. };
  15100. /**
  15101. * Is this node enabled.
  15102. * 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.
  15103. * @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.
  15104. * @return {boolean} whether this node (and its parent) is enabled.
  15105. * @see setEnabled
  15106. */
  15107. Node.prototype.isEnabled = function (checkAncestors) {
  15108. if (checkAncestors === void 0) { checkAncestors = true; }
  15109. if (checkAncestors === false) {
  15110. return this._isEnabled;
  15111. }
  15112. if (this._isEnabled === false) {
  15113. return false;
  15114. }
  15115. if (this.parent !== undefined && this.parent !== null) {
  15116. return this.parent.isEnabled(checkAncestors);
  15117. }
  15118. return true;
  15119. };
  15120. /**
  15121. * Set the enabled state of this node.
  15122. * @param {boolean} value - the new enabled state
  15123. * @see isEnabled
  15124. */
  15125. Node.prototype.setEnabled = function (value) {
  15126. this._isEnabled = value;
  15127. };
  15128. /**
  15129. * Is this node a descendant of the given node.
  15130. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  15131. * @param {BABYLON.Node} ancestor - The parent node to inspect
  15132. * @see parent
  15133. */
  15134. Node.prototype.isDescendantOf = function (ancestor) {
  15135. if (this.parent) {
  15136. if (this.parent === ancestor) {
  15137. return true;
  15138. }
  15139. return this.parent.isDescendantOf(ancestor);
  15140. }
  15141. return false;
  15142. };
  15143. /**
  15144. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  15145. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  15146. * @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.
  15147. * @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.
  15148. */
  15149. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15150. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15151. if (!this._children) {
  15152. return;
  15153. }
  15154. for (var index = 0; index < this._children.length; index++) {
  15155. var item = this._children[index];
  15156. if (!predicate || predicate(item)) {
  15157. results.push(item);
  15158. }
  15159. if (!directDescendantsOnly) {
  15160. item._getDescendants(results, false, predicate);
  15161. }
  15162. }
  15163. };
  15164. /**
  15165. * Will return all nodes that have this node as ascendant.
  15166. * @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.
  15167. * @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.
  15168. * @return {BABYLON.Node[]} all children nodes of all types.
  15169. */
  15170. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15171. var results = new Array();
  15172. this._getDescendants(results, directDescendantsOnly, predicate);
  15173. return results;
  15174. };
  15175. /**
  15176. * Get all child-meshes of this node.
  15177. */
  15178. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15179. var results = [];
  15180. this._getDescendants(results, directDescendantsOnly, function (node) {
  15181. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15182. });
  15183. return results;
  15184. };
  15185. /**
  15186. * Get all child-transformNodes of this node.
  15187. */
  15188. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15189. var results = [];
  15190. this._getDescendants(results, directDescendantsOnly, function (node) {
  15191. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15192. });
  15193. return results;
  15194. };
  15195. /**
  15196. * Get all direct children of this node.
  15197. */
  15198. Node.prototype.getChildren = function (predicate) {
  15199. return this.getDescendants(true, predicate);
  15200. };
  15201. Node.prototype._setReady = function (state) {
  15202. if (state === this._isReady) {
  15203. return;
  15204. }
  15205. if (!state) {
  15206. this._isReady = false;
  15207. return;
  15208. }
  15209. this._isReady = true;
  15210. if (this.onReady) {
  15211. this.onReady(this);
  15212. }
  15213. };
  15214. Node.prototype.getAnimationByName = function (name) {
  15215. for (var i = 0; i < this.animations.length; i++) {
  15216. var animation = this.animations[i];
  15217. if (animation.name === name) {
  15218. return animation;
  15219. }
  15220. }
  15221. return null;
  15222. };
  15223. Node.prototype.createAnimationRange = function (name, from, to) {
  15224. // check name not already in use
  15225. if (!this._ranges[name]) {
  15226. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15227. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15228. if (this.animations[i]) {
  15229. this.animations[i].createRange(name, from, to);
  15230. }
  15231. }
  15232. }
  15233. };
  15234. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15235. if (deleteFrames === void 0) { deleteFrames = true; }
  15236. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15237. if (this.animations[i]) {
  15238. this.animations[i].deleteRange(name, deleteFrames);
  15239. }
  15240. }
  15241. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15242. };
  15243. Node.prototype.getAnimationRange = function (name) {
  15244. return this._ranges[name];
  15245. };
  15246. /**
  15247. * Will start the animation sequence
  15248. * @param name defines the range frames for animation sequence
  15249. * @param loop defines if the animation should loop (false by default)
  15250. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15251. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15252. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  15253. */
  15254. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15255. var range = this.getAnimationRange(name);
  15256. if (!range) {
  15257. return null;
  15258. }
  15259. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15260. };
  15261. Node.prototype.serializeAnimationRanges = function () {
  15262. var serializationRanges = [];
  15263. for (var name in this._ranges) {
  15264. var localRange = this._ranges[name];
  15265. if (!localRange) {
  15266. continue;
  15267. }
  15268. var range = {};
  15269. range.name = name;
  15270. range.from = localRange.from;
  15271. range.to = localRange.to;
  15272. serializationRanges.push(range);
  15273. }
  15274. return serializationRanges;
  15275. };
  15276. // override it in derived class
  15277. Node.prototype.computeWorldMatrix = function (force) {
  15278. return BABYLON.Matrix.Identity();
  15279. };
  15280. Node.prototype.dispose = function () {
  15281. this.parent = null;
  15282. // Callback
  15283. this.onDisposeObservable.notifyObservers(this);
  15284. this.onDisposeObservable.clear();
  15285. // Behaviors
  15286. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15287. var behavior = _a[_i];
  15288. behavior.detach();
  15289. }
  15290. this._behaviors = [];
  15291. };
  15292. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15293. if (parsedNode.ranges) {
  15294. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15295. var data = parsedNode.ranges[index];
  15296. node.createAnimationRange(data.name, data.from, data.to);
  15297. }
  15298. }
  15299. };
  15300. __decorate([
  15301. BABYLON.serialize()
  15302. ], Node.prototype, "name", void 0);
  15303. __decorate([
  15304. BABYLON.serialize()
  15305. ], Node.prototype, "id", void 0);
  15306. __decorate([
  15307. BABYLON.serialize()
  15308. ], Node.prototype, "uniqueId", void 0);
  15309. __decorate([
  15310. BABYLON.serialize()
  15311. ], Node.prototype, "state", void 0);
  15312. __decorate([
  15313. BABYLON.serialize()
  15314. ], Node.prototype, "metadata", void 0);
  15315. return Node;
  15316. }());
  15317. BABYLON.Node = Node;
  15318. })(BABYLON || (BABYLON = {}));
  15319. //# sourceMappingURL=babylon.node.js.map
  15320. var BABYLON;
  15321. (function (BABYLON) {
  15322. var BoundingSphere = /** @class */ (function () {
  15323. function BoundingSphere(minimum, maximum) {
  15324. this.minimum = minimum;
  15325. this.maximum = maximum;
  15326. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15327. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15328. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15329. this.radius = distance * 0.5;
  15330. this.centerWorld = BABYLON.Vector3.Zero();
  15331. this._update(BABYLON.Matrix.Identity());
  15332. }
  15333. // Methods
  15334. BoundingSphere.prototype._update = function (world) {
  15335. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15336. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15337. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15338. };
  15339. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15340. for (var i = 0; i < 6; i++) {
  15341. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15342. return false;
  15343. }
  15344. return true;
  15345. };
  15346. BoundingSphere.prototype.intersectsPoint = function (point) {
  15347. var x = this.centerWorld.x - point.x;
  15348. var y = this.centerWorld.y - point.y;
  15349. var z = this.centerWorld.z - point.z;
  15350. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15351. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15352. return false;
  15353. return true;
  15354. };
  15355. // Statics
  15356. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15357. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15358. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15359. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15360. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15361. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15362. return false;
  15363. return true;
  15364. };
  15365. return BoundingSphere;
  15366. }());
  15367. BABYLON.BoundingSphere = BoundingSphere;
  15368. })(BABYLON || (BABYLON = {}));
  15369. //# sourceMappingURL=babylon.boundingSphere.js.map
  15370. var BABYLON;
  15371. (function (BABYLON) {
  15372. var BoundingBox = /** @class */ (function () {
  15373. function BoundingBox(minimum, maximum) {
  15374. this.minimum = minimum;
  15375. this.maximum = maximum;
  15376. this.vectors = new Array();
  15377. this.vectorsWorld = new Array();
  15378. // Bounding vectors
  15379. this.vectors.push(this.minimum.clone());
  15380. this.vectors.push(this.maximum.clone());
  15381. this.vectors.push(this.minimum.clone());
  15382. this.vectors[2].x = this.maximum.x;
  15383. this.vectors.push(this.minimum.clone());
  15384. this.vectors[3].y = this.maximum.y;
  15385. this.vectors.push(this.minimum.clone());
  15386. this.vectors[4].z = this.maximum.z;
  15387. this.vectors.push(this.maximum.clone());
  15388. this.vectors[5].z = this.minimum.z;
  15389. this.vectors.push(this.maximum.clone());
  15390. this.vectors[6].x = this.minimum.x;
  15391. this.vectors.push(this.maximum.clone());
  15392. this.vectors[7].y = this.minimum.y;
  15393. // OBB
  15394. this.center = this.maximum.add(this.minimum).scale(0.5);
  15395. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15396. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15397. // World
  15398. for (var index = 0; index < this.vectors.length; index++) {
  15399. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15400. }
  15401. this.minimumWorld = BABYLON.Vector3.Zero();
  15402. this.maximumWorld = BABYLON.Vector3.Zero();
  15403. this.centerWorld = BABYLON.Vector3.Zero();
  15404. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15405. this._update(BABYLON.Matrix.Identity());
  15406. }
  15407. // Methods
  15408. BoundingBox.prototype.getWorldMatrix = function () {
  15409. return this._worldMatrix;
  15410. };
  15411. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15412. this._worldMatrix.copyFrom(matrix);
  15413. return this;
  15414. };
  15415. BoundingBox.prototype._update = function (world) {
  15416. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15417. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15418. for (var index = 0; index < this.vectors.length; index++) {
  15419. var v = this.vectorsWorld[index];
  15420. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15421. if (v.x < this.minimumWorld.x)
  15422. this.minimumWorld.x = v.x;
  15423. if (v.y < this.minimumWorld.y)
  15424. this.minimumWorld.y = v.y;
  15425. if (v.z < this.minimumWorld.z)
  15426. this.minimumWorld.z = v.z;
  15427. if (v.x > this.maximumWorld.x)
  15428. this.maximumWorld.x = v.x;
  15429. if (v.y > this.maximumWorld.y)
  15430. this.maximumWorld.y = v.y;
  15431. if (v.z > this.maximumWorld.z)
  15432. this.maximumWorld.z = v.z;
  15433. }
  15434. // Extend
  15435. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15436. this.extendSizeWorld.scaleInPlace(0.5);
  15437. // OBB
  15438. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15439. this.centerWorld.scaleInPlace(0.5);
  15440. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15441. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15442. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15443. this._worldMatrix = world;
  15444. };
  15445. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15446. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15447. };
  15448. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15449. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15450. };
  15451. BoundingBox.prototype.intersectsPoint = function (point) {
  15452. var delta = -BABYLON.Epsilon;
  15453. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15454. return false;
  15455. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15456. return false;
  15457. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15458. return false;
  15459. return true;
  15460. };
  15461. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15462. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15463. };
  15464. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15465. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15466. return false;
  15467. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15468. return false;
  15469. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15470. return false;
  15471. return true;
  15472. };
  15473. // Statics
  15474. BoundingBox.Intersects = function (box0, box1) {
  15475. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15476. return false;
  15477. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15478. return false;
  15479. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15480. return false;
  15481. return true;
  15482. };
  15483. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15484. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15485. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15486. return (num <= (sphereRadius * sphereRadius));
  15487. };
  15488. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15489. for (var p = 0; p < 6; p++) {
  15490. for (var i = 0; i < 8; i++) {
  15491. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15492. return false;
  15493. }
  15494. }
  15495. }
  15496. return true;
  15497. };
  15498. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15499. for (var p = 0; p < 6; p++) {
  15500. var inCount = 8;
  15501. for (var i = 0; i < 8; i++) {
  15502. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15503. --inCount;
  15504. }
  15505. else {
  15506. break;
  15507. }
  15508. }
  15509. if (inCount === 0)
  15510. return false;
  15511. }
  15512. return true;
  15513. };
  15514. return BoundingBox;
  15515. }());
  15516. BABYLON.BoundingBox = BoundingBox;
  15517. })(BABYLON || (BABYLON = {}));
  15518. //# sourceMappingURL=babylon.boundingBox.js.map
  15519. var BABYLON;
  15520. (function (BABYLON) {
  15521. var computeBoxExtents = function (axis, box) {
  15522. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15523. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15524. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15525. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15526. var r = r0 + r1 + r2;
  15527. return {
  15528. min: p - r,
  15529. max: p + r
  15530. };
  15531. };
  15532. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15533. var axisOverlap = function (axis, box0, box1) {
  15534. var result0 = computeBoxExtents(axis, box0);
  15535. var result1 = computeBoxExtents(axis, box1);
  15536. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15537. };
  15538. var BoundingInfo = /** @class */ (function () {
  15539. function BoundingInfo(minimum, maximum) {
  15540. this.minimum = minimum;
  15541. this.maximum = maximum;
  15542. this._isLocked = false;
  15543. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15544. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15545. }
  15546. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15547. get: function () {
  15548. return this._isLocked;
  15549. },
  15550. set: function (value) {
  15551. this._isLocked = value;
  15552. },
  15553. enumerable: true,
  15554. configurable: true
  15555. });
  15556. // Methods
  15557. BoundingInfo.prototype.update = function (world) {
  15558. if (this._isLocked) {
  15559. return;
  15560. }
  15561. this.boundingBox._update(world);
  15562. this.boundingSphere._update(world);
  15563. };
  15564. /**
  15565. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15566. * @param center New center of the bounding info
  15567. * @param extend New extend of the bounding info
  15568. */
  15569. BoundingInfo.prototype.centerOn = function (center, extend) {
  15570. this.minimum = center.subtract(extend);
  15571. this.maximum = center.add(extend);
  15572. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15573. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15574. return this;
  15575. };
  15576. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15577. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15578. return false;
  15579. return this.boundingBox.isInFrustum(frustumPlanes);
  15580. };
  15581. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15582. /**
  15583. * Gets the world distance between the min and max points of the bounding box
  15584. */
  15585. get: function () {
  15586. var boundingBox = this.boundingBox;
  15587. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15588. return size.length();
  15589. },
  15590. enumerable: true,
  15591. configurable: true
  15592. });
  15593. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15594. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15595. };
  15596. BoundingInfo.prototype._checkCollision = function (collider) {
  15597. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15598. };
  15599. BoundingInfo.prototype.intersectsPoint = function (point) {
  15600. if (!this.boundingSphere.centerWorld) {
  15601. return false;
  15602. }
  15603. if (!this.boundingSphere.intersectsPoint(point)) {
  15604. return false;
  15605. }
  15606. if (!this.boundingBox.intersectsPoint(point)) {
  15607. return false;
  15608. }
  15609. return true;
  15610. };
  15611. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15612. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15613. return false;
  15614. }
  15615. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15616. return false;
  15617. }
  15618. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15619. return false;
  15620. }
  15621. if (!precise) {
  15622. return true;
  15623. }
  15624. var box0 = this.boundingBox;
  15625. var box1 = boundingInfo.boundingBox;
  15626. if (!axisOverlap(box0.directions[0], box0, box1))
  15627. return false;
  15628. if (!axisOverlap(box0.directions[1], box0, box1))
  15629. return false;
  15630. if (!axisOverlap(box0.directions[2], box0, box1))
  15631. return false;
  15632. if (!axisOverlap(box1.directions[0], box0, box1))
  15633. return false;
  15634. if (!axisOverlap(box1.directions[1], box0, box1))
  15635. return false;
  15636. if (!axisOverlap(box1.directions[2], box0, box1))
  15637. return false;
  15638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15639. return false;
  15640. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15641. return false;
  15642. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15643. return false;
  15644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15645. return false;
  15646. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15647. return false;
  15648. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15649. return false;
  15650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15651. return false;
  15652. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15653. return false;
  15654. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15655. return false;
  15656. return true;
  15657. };
  15658. return BoundingInfo;
  15659. }());
  15660. BABYLON.BoundingInfo = BoundingInfo;
  15661. })(BABYLON || (BABYLON = {}));
  15662. //# sourceMappingURL=babylon.boundingInfo.js.map
  15663. var BABYLON;
  15664. (function (BABYLON) {
  15665. var TransformNode = /** @class */ (function (_super) {
  15666. __extends(TransformNode, _super);
  15667. function TransformNode(name, scene, isPure) {
  15668. if (scene === void 0) { scene = null; }
  15669. if (isPure === void 0) { isPure = true; }
  15670. var _this = _super.call(this, name, scene) || this;
  15671. // Properties
  15672. _this._rotation = BABYLON.Vector3.Zero();
  15673. _this._scaling = BABYLON.Vector3.One();
  15674. _this._isDirty = false;
  15675. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15676. _this.scalingDeterminant = 1;
  15677. _this.infiniteDistance = false;
  15678. _this.position = BABYLON.Vector3.Zero();
  15679. _this._localWorld = BABYLON.Matrix.Zero();
  15680. _this._worldMatrix = BABYLON.Matrix.Zero();
  15681. _this._worldMatrixDeterminant = 0;
  15682. _this._absolutePosition = BABYLON.Vector3.Zero();
  15683. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15684. _this._postMultiplyPivotMatrix = false;
  15685. _this._isWorldMatrixFrozen = false;
  15686. /**
  15687. * An event triggered after the world matrix is updated
  15688. * @type {BABYLON.Observable}
  15689. */
  15690. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15691. _this._nonUniformScaling = false;
  15692. if (isPure) {
  15693. _this.getScene().addTransformNode(_this);
  15694. }
  15695. return _this;
  15696. }
  15697. Object.defineProperty(TransformNode.prototype, "rotation", {
  15698. /**
  15699. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15700. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15701. * Default : (0.0, 0.0, 0.0)
  15702. */
  15703. get: function () {
  15704. return this._rotation;
  15705. },
  15706. set: function (newRotation) {
  15707. this._rotation = newRotation;
  15708. },
  15709. enumerable: true,
  15710. configurable: true
  15711. });
  15712. Object.defineProperty(TransformNode.prototype, "scaling", {
  15713. /**
  15714. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15715. * Default : (1.0, 1.0, 1.0)
  15716. */
  15717. get: function () {
  15718. return this._scaling;
  15719. },
  15720. /**
  15721. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15722. * Default : (1.0, 1.0, 1.0)
  15723. */
  15724. set: function (newScaling) {
  15725. this._scaling = newScaling;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15731. /**
  15732. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15733. * It's null by default.
  15734. * 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)
  15735. */
  15736. get: function () {
  15737. return this._rotationQuaternion;
  15738. },
  15739. set: function (quaternion) {
  15740. this._rotationQuaternion = quaternion;
  15741. //reset the rotation vector.
  15742. if (quaternion && this.rotation.length()) {
  15743. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15744. }
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. /**
  15750. * Returns the latest update of the World matrix
  15751. * Returns a Matrix.
  15752. */
  15753. TransformNode.prototype.getWorldMatrix = function () {
  15754. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15755. this.computeWorldMatrix();
  15756. }
  15757. return this._worldMatrix;
  15758. };
  15759. /**
  15760. * Returns the latest update of the World matrix determinant.
  15761. */
  15762. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15763. return this._worldMatrixDeterminant;
  15764. };
  15765. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15766. /**
  15767. * Returns directly the latest state of the mesh World matrix.
  15768. * A Matrix is returned.
  15769. */
  15770. get: function () {
  15771. return this._worldMatrix;
  15772. },
  15773. enumerable: true,
  15774. configurable: true
  15775. });
  15776. /**
  15777. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15778. * Returns the AbstractMesh.
  15779. */
  15780. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15781. this._poseMatrix.copyFrom(matrix);
  15782. return this;
  15783. };
  15784. /**
  15785. * Returns the mesh Pose matrix.
  15786. * Returned object : Matrix
  15787. */
  15788. TransformNode.prototype.getPoseMatrix = function () {
  15789. return this._poseMatrix;
  15790. };
  15791. TransformNode.prototype._isSynchronized = function () {
  15792. if (this._isDirty) {
  15793. return false;
  15794. }
  15795. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15796. return false;
  15797. if (this._cache.pivotMatrixUpdated) {
  15798. return false;
  15799. }
  15800. if (this.infiniteDistance) {
  15801. return false;
  15802. }
  15803. if (!this._cache.position.equals(this.position))
  15804. return false;
  15805. if (this.rotationQuaternion) {
  15806. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15807. return false;
  15808. }
  15809. if (!this._cache.rotation.equals(this.rotation))
  15810. return false;
  15811. if (!this._cache.scaling.equals(this.scaling))
  15812. return false;
  15813. return true;
  15814. };
  15815. TransformNode.prototype._initCache = function () {
  15816. _super.prototype._initCache.call(this);
  15817. this._cache.localMatrixUpdated = false;
  15818. this._cache.position = BABYLON.Vector3.Zero();
  15819. this._cache.scaling = BABYLON.Vector3.Zero();
  15820. this._cache.rotation = BABYLON.Vector3.Zero();
  15821. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15822. this._cache.billboardMode = -1;
  15823. };
  15824. TransformNode.prototype.markAsDirty = function (property) {
  15825. if (property === "rotation") {
  15826. this.rotationQuaternion = null;
  15827. }
  15828. this._currentRenderId = Number.MAX_VALUE;
  15829. this._isDirty = true;
  15830. return this;
  15831. };
  15832. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15833. /**
  15834. * Returns the current mesh absolute position.
  15835. * Retuns a Vector3.
  15836. */
  15837. get: function () {
  15838. return this._absolutePosition;
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. /**
  15844. * Sets a new matrix to apply before all other transformation
  15845. * @param matrix defines the transform matrix
  15846. * @returns the current TransformNode
  15847. */
  15848. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15849. return this.setPivotMatrix(matrix, false);
  15850. };
  15851. /**
  15852. * Sets a new pivot matrix to the current node
  15853. * @param matrix defines the new pivot matrix to use
  15854. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  15855. * @returns the current TransformNode
  15856. */
  15857. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15858. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15859. this._pivotMatrix = matrix.clone();
  15860. this._cache.pivotMatrixUpdated = true;
  15861. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15862. if (this._postMultiplyPivotMatrix) {
  15863. if (!this._pivotMatrixInverse) {
  15864. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15865. }
  15866. else {
  15867. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15868. }
  15869. }
  15870. return this;
  15871. };
  15872. /**
  15873. * Returns the mesh pivot matrix.
  15874. * Default : Identity.
  15875. * A Matrix is returned.
  15876. */
  15877. TransformNode.prototype.getPivotMatrix = function () {
  15878. return this._pivotMatrix;
  15879. };
  15880. /**
  15881. * Prevents the World matrix to be computed any longer.
  15882. * Returns the AbstractMesh.
  15883. */
  15884. TransformNode.prototype.freezeWorldMatrix = function () {
  15885. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15886. this.computeWorldMatrix(true);
  15887. this._isWorldMatrixFrozen = true;
  15888. return this;
  15889. };
  15890. /**
  15891. * Allows back the World matrix computation.
  15892. * Returns the AbstractMesh.
  15893. */
  15894. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15895. this._isWorldMatrixFrozen = false;
  15896. this.computeWorldMatrix(true);
  15897. return this;
  15898. };
  15899. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15900. /**
  15901. * True if the World matrix has been frozen.
  15902. * Returns a boolean.
  15903. */
  15904. get: function () {
  15905. return this._isWorldMatrixFrozen;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. /**
  15911. * Retuns the mesh absolute position in the World.
  15912. * Returns a Vector3.
  15913. */
  15914. TransformNode.prototype.getAbsolutePosition = function () {
  15915. this.computeWorldMatrix();
  15916. return this._absolutePosition;
  15917. };
  15918. /**
  15919. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15920. * Returns the AbstractMesh.
  15921. */
  15922. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15923. if (!absolutePosition) {
  15924. return this;
  15925. }
  15926. var absolutePositionX;
  15927. var absolutePositionY;
  15928. var absolutePositionZ;
  15929. if (absolutePosition.x === undefined) {
  15930. if (arguments.length < 3) {
  15931. return this;
  15932. }
  15933. absolutePositionX = arguments[0];
  15934. absolutePositionY = arguments[1];
  15935. absolutePositionZ = arguments[2];
  15936. }
  15937. else {
  15938. absolutePositionX = absolutePosition.x;
  15939. absolutePositionY = absolutePosition.y;
  15940. absolutePositionZ = absolutePosition.z;
  15941. }
  15942. if (this.parent) {
  15943. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15944. invertParentWorldMatrix.invert();
  15945. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15946. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15947. }
  15948. else {
  15949. this.position.x = absolutePositionX;
  15950. this.position.y = absolutePositionY;
  15951. this.position.z = absolutePositionZ;
  15952. }
  15953. return this;
  15954. };
  15955. /**
  15956. * Sets the mesh position in its local space.
  15957. * Returns the AbstractMesh.
  15958. */
  15959. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15960. this.computeWorldMatrix();
  15961. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15962. return this;
  15963. };
  15964. /**
  15965. * Returns the mesh position in the local space from the current World matrix values.
  15966. * Returns a new Vector3.
  15967. */
  15968. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15969. this.computeWorldMatrix();
  15970. var invLocalWorldMatrix = this._localWorld.clone();
  15971. invLocalWorldMatrix.invert();
  15972. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15973. };
  15974. /**
  15975. * Translates the mesh along the passed Vector3 in its local space.
  15976. * Returns the AbstractMesh.
  15977. */
  15978. TransformNode.prototype.locallyTranslate = function (vector3) {
  15979. this.computeWorldMatrix(true);
  15980. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15981. return this;
  15982. };
  15983. /**
  15984. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15985. * @param targetPoint the position (must be in same space as current mesh) to look at
  15986. * @param yawCor optional yaw (y-axis) correction in radians
  15987. * @param pitchCor optional pitch (x-axis) correction in radians
  15988. * @param rollCor optional roll (z-axis) correction in radians
  15989. * @param space the choosen space of the target
  15990. * @returns the TransformNode.
  15991. */
  15992. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15993. if (yawCor === void 0) { yawCor = 0; }
  15994. if (pitchCor === void 0) { pitchCor = 0; }
  15995. if (rollCor === void 0) { rollCor = 0; }
  15996. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15997. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15998. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15999. targetPoint.subtractToRef(pos, dv);
  16000. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16001. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16002. var pitch = Math.atan2(dv.y, len);
  16003. if (this.rotationQuaternion) {
  16004. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16005. }
  16006. else {
  16007. this.rotation.x = pitch + pitchCor;
  16008. this.rotation.y = yaw + yawCor;
  16009. this.rotation.z = rollCor;
  16010. }
  16011. return this;
  16012. };
  16013. /**
  16014. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16015. * This Vector3 is expressed in the World space.
  16016. */
  16017. TransformNode.prototype.getDirection = function (localAxis) {
  16018. var result = BABYLON.Vector3.Zero();
  16019. this.getDirectionToRef(localAxis, result);
  16020. return result;
  16021. };
  16022. /**
  16023. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16024. * localAxis is expressed in the mesh local space.
  16025. * result is computed in the Wordl space from the mesh World matrix.
  16026. * Returns the AbstractMesh.
  16027. */
  16028. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16029. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16030. return this;
  16031. };
  16032. /**
  16033. * Sets a new pivot point to the current node
  16034. * @param point defines the new pivot point to use
  16035. * @param space defines if the point is in world or local space (local by default)
  16036. * @returns the current TransformNode
  16037. */
  16038. TransformNode.prototype.setPivotPoint = function (point, space) {
  16039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16040. if (this.getScene().getRenderId() == 0) {
  16041. this.computeWorldMatrix(true);
  16042. }
  16043. var wm = this.getWorldMatrix();
  16044. if (space == BABYLON.Space.WORLD) {
  16045. var tmat = BABYLON.Tmp.Matrix[0];
  16046. wm.invertToRef(tmat);
  16047. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16048. }
  16049. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16050. };
  16051. /**
  16052. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16053. */
  16054. TransformNode.prototype.getPivotPoint = function () {
  16055. var point = BABYLON.Vector3.Zero();
  16056. this.getPivotPointToRef(point);
  16057. return point;
  16058. };
  16059. /**
  16060. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16061. * Returns the AbstractMesh.
  16062. */
  16063. TransformNode.prototype.getPivotPointToRef = function (result) {
  16064. result.x = -this._pivotMatrix.m[12];
  16065. result.y = -this._pivotMatrix.m[13];
  16066. result.z = -this._pivotMatrix.m[14];
  16067. return this;
  16068. };
  16069. /**
  16070. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16071. */
  16072. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16073. var point = BABYLON.Vector3.Zero();
  16074. this.getAbsolutePivotPointToRef(point);
  16075. return point;
  16076. };
  16077. /**
  16078. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16079. * Returns the AbstractMesh.
  16080. */
  16081. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16082. result.x = this._pivotMatrix.m[12];
  16083. result.y = this._pivotMatrix.m[13];
  16084. result.z = this._pivotMatrix.m[14];
  16085. this.getPivotPointToRef(result);
  16086. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16087. return this;
  16088. };
  16089. /**
  16090. * Defines the passed node as the parent of the current node.
  16091. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16092. * Returns the TransformNode.
  16093. */
  16094. TransformNode.prototype.setParent = function (node) {
  16095. if (node === null) {
  16096. var rotation = BABYLON.Tmp.Quaternion[0];
  16097. var position = BABYLON.Tmp.Vector3[0];
  16098. var scale = BABYLON.Tmp.Vector3[1];
  16099. if (this.parent && this.parent.computeWorldMatrix) {
  16100. this.parent.computeWorldMatrix(true);
  16101. }
  16102. this.computeWorldMatrix(true);
  16103. this.getWorldMatrix().decompose(scale, rotation, position);
  16104. if (this.rotationQuaternion) {
  16105. this.rotationQuaternion.copyFrom(rotation);
  16106. }
  16107. else {
  16108. rotation.toEulerAnglesToRef(this.rotation);
  16109. }
  16110. this.scaling.x = scale.x;
  16111. this.scaling.y = scale.y;
  16112. this.scaling.z = scale.z;
  16113. this.position.x = position.x;
  16114. this.position.y = position.y;
  16115. this.position.z = position.z;
  16116. }
  16117. else {
  16118. var rotation = BABYLON.Tmp.Quaternion[0];
  16119. var position = BABYLON.Tmp.Vector3[0];
  16120. var scale = BABYLON.Tmp.Vector3[1];
  16121. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16122. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16123. this.computeWorldMatrix(true);
  16124. node.computeWorldMatrix(true);
  16125. node.getWorldMatrix().invertToRef(invParentMatrix);
  16126. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16127. diffMatrix.decompose(scale, rotation, position);
  16128. if (this.rotationQuaternion) {
  16129. this.rotationQuaternion.copyFrom(rotation);
  16130. }
  16131. else {
  16132. rotation.toEulerAnglesToRef(this.rotation);
  16133. }
  16134. this.position.x = position.x;
  16135. this.position.y = position.y;
  16136. this.position.z = position.z;
  16137. this.scaling.x = scale.x;
  16138. this.scaling.y = scale.y;
  16139. this.scaling.z = scale.z;
  16140. }
  16141. this.parent = node;
  16142. return this;
  16143. };
  16144. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16145. get: function () {
  16146. return this._nonUniformScaling;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16152. if (this._nonUniformScaling === value) {
  16153. return false;
  16154. }
  16155. this._nonUniformScaling = true;
  16156. return true;
  16157. };
  16158. /**
  16159. * Attach the current TransformNode to another TransformNode associated with a bone
  16160. * @param bone Bone affecting the TransformNode
  16161. * @param affectedTransformNode TransformNode associated with the bone
  16162. */
  16163. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16164. this._transformToBoneReferal = affectedTransformNode;
  16165. this.parent = bone;
  16166. if (bone.getWorldMatrix().determinant() < 0) {
  16167. this.scalingDeterminant *= -1;
  16168. }
  16169. return this;
  16170. };
  16171. TransformNode.prototype.detachFromBone = function () {
  16172. if (!this.parent) {
  16173. return this;
  16174. }
  16175. if (this.parent.getWorldMatrix().determinant() < 0) {
  16176. this.scalingDeterminant *= -1;
  16177. }
  16178. this._transformToBoneReferal = null;
  16179. this.parent = null;
  16180. return this;
  16181. };
  16182. /**
  16183. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16184. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16185. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16186. * The passed axis is also normalized.
  16187. * Returns the AbstractMesh.
  16188. */
  16189. TransformNode.prototype.rotate = function (axis, amount, space) {
  16190. axis.normalize();
  16191. if (!this.rotationQuaternion) {
  16192. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16193. this.rotation = BABYLON.Vector3.Zero();
  16194. }
  16195. var rotationQuaternion;
  16196. if (!space || space === BABYLON.Space.LOCAL) {
  16197. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16198. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16199. }
  16200. else {
  16201. if (this.parent) {
  16202. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16203. invertParentWorldMatrix.invert();
  16204. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16205. }
  16206. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16207. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16208. }
  16209. return this;
  16210. };
  16211. /**
  16212. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16213. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16214. * The passed axis is also normalized.
  16215. * Returns the AbstractMesh.
  16216. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16217. */
  16218. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16219. axis.normalize();
  16220. if (!this.rotationQuaternion) {
  16221. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16222. this.rotation.copyFromFloats(0, 0, 0);
  16223. }
  16224. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16225. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16226. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16227. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16228. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16229. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16230. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16231. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16232. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16233. return this;
  16234. };
  16235. /**
  16236. * Translates the mesh along the axis vector for the passed distance in the given space.
  16237. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16238. * Returns the AbstractMesh.
  16239. */
  16240. TransformNode.prototype.translate = function (axis, distance, space) {
  16241. var displacementVector = axis.scale(distance);
  16242. if (!space || space === BABYLON.Space.LOCAL) {
  16243. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16244. this.setPositionWithLocalVector(tempV3);
  16245. }
  16246. else {
  16247. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16248. }
  16249. return this;
  16250. };
  16251. /**
  16252. * Adds a rotation step to the mesh current rotation.
  16253. * x, y, z are Euler angles expressed in radians.
  16254. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16255. * This means this rotation is made in the mesh local space only.
  16256. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16257. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16258. * ```javascript
  16259. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16260. * ```
  16261. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16262. * 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.
  16263. * Returns the AbstractMesh.
  16264. */
  16265. TransformNode.prototype.addRotation = function (x, y, z) {
  16266. var rotationQuaternion;
  16267. if (this.rotationQuaternion) {
  16268. rotationQuaternion = this.rotationQuaternion;
  16269. }
  16270. else {
  16271. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16272. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16273. }
  16274. var accumulation = BABYLON.Tmp.Quaternion[0];
  16275. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16276. rotationQuaternion.multiplyInPlace(accumulation);
  16277. if (!this.rotationQuaternion) {
  16278. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16279. }
  16280. return this;
  16281. };
  16282. /**
  16283. * Computes the mesh World matrix and returns it.
  16284. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16285. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16286. * If the parameter `force`is set to `true`, the actual computation is done.
  16287. * Returns the mesh World Matrix.
  16288. */
  16289. TransformNode.prototype.computeWorldMatrix = function (force) {
  16290. if (this._isWorldMatrixFrozen) {
  16291. return this._worldMatrix;
  16292. }
  16293. if (!force && this.isSynchronized(true)) {
  16294. return this._worldMatrix;
  16295. }
  16296. this._cache.position.copyFrom(this.position);
  16297. this._cache.scaling.copyFrom(this.scaling);
  16298. this._cache.pivotMatrixUpdated = false;
  16299. this._cache.billboardMode = this.billboardMode;
  16300. this._currentRenderId = this.getScene().getRenderId();
  16301. this._isDirty = false;
  16302. // Scaling
  16303. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16304. // Rotation
  16305. //rotate, if quaternion is set and rotation was used
  16306. if (this.rotationQuaternion) {
  16307. var len = this.rotation.length();
  16308. if (len) {
  16309. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16310. this.rotation.copyFromFloats(0, 0, 0);
  16311. }
  16312. }
  16313. if (this.rotationQuaternion) {
  16314. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16315. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16316. }
  16317. else {
  16318. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16319. this._cache.rotation.copyFrom(this.rotation);
  16320. }
  16321. // Translation
  16322. var camera = this.getScene().activeCamera;
  16323. if (this.infiniteDistance && !this.parent && camera) {
  16324. var cameraWorldMatrix = camera.getWorldMatrix();
  16325. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16326. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16327. }
  16328. else {
  16329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16330. }
  16331. // Composing transformations
  16332. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16333. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16334. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16335. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16336. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16337. // Need to decompose each rotation here
  16338. var currentPosition = BABYLON.Tmp.Vector3[3];
  16339. if (this.parent && this.parent.getWorldMatrix) {
  16340. if (this._transformToBoneReferal) {
  16341. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16342. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16343. }
  16344. else {
  16345. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16346. }
  16347. }
  16348. else {
  16349. currentPosition.copyFrom(this.position);
  16350. }
  16351. currentPosition.subtractInPlace(camera.globalPosition);
  16352. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16353. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16354. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16355. }
  16356. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16357. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16358. }
  16359. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16360. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16361. }
  16362. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16363. }
  16364. else {
  16365. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16366. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16367. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16368. }
  16369. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16370. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16371. }
  16372. // Local world
  16373. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16374. // Parent
  16375. if (this.parent && this.parent.getWorldMatrix) {
  16376. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16377. if (this._transformToBoneReferal) {
  16378. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16379. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16380. }
  16381. else {
  16382. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16383. }
  16384. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16385. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16386. this._worldMatrix.copyFrom(this._localWorld);
  16387. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16388. }
  16389. else {
  16390. if (this._transformToBoneReferal) {
  16391. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16392. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16393. }
  16394. else {
  16395. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16396. }
  16397. }
  16398. this._markSyncedWithParent();
  16399. }
  16400. else {
  16401. this._worldMatrix.copyFrom(this._localWorld);
  16402. }
  16403. // Post multiply inverse of pivotMatrix
  16404. if (this._postMultiplyPivotMatrix) {
  16405. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16406. }
  16407. // Normal matrix
  16408. if (this.scaling.isNonUniform) {
  16409. this._updateNonUniformScalingState(true);
  16410. }
  16411. else if (this.parent && this.parent._nonUniformScaling) {
  16412. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16413. }
  16414. else {
  16415. this._updateNonUniformScalingState(false);
  16416. }
  16417. this._afterComputeWorldMatrix();
  16418. // Absolute position
  16419. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16420. // Callbacks
  16421. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16422. if (!this._poseMatrix) {
  16423. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16424. }
  16425. // Cache the determinant
  16426. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16427. return this._worldMatrix;
  16428. };
  16429. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16430. };
  16431. /**
  16432. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16433. * @param func: callback function to add
  16434. *
  16435. * Returns the TransformNode.
  16436. */
  16437. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16438. this.onAfterWorldMatrixUpdateObservable.add(func);
  16439. return this;
  16440. };
  16441. /**
  16442. * Removes a registered callback function.
  16443. * Returns the TransformNode.
  16444. */
  16445. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16446. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16447. return this;
  16448. };
  16449. /**
  16450. * Clone the current transform node
  16451. * Returns the new transform node
  16452. * @param name Name of the new clone
  16453. * @param newParent New parent for the clone
  16454. * @param doNotCloneChildren Do not clone children hierarchy
  16455. */
  16456. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16457. var _this = this;
  16458. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16459. result.name = name;
  16460. result.id = name;
  16461. if (newParent) {
  16462. result.parent = newParent;
  16463. }
  16464. if (!doNotCloneChildren) {
  16465. // Children
  16466. var directDescendants = this.getDescendants(true);
  16467. for (var index = 0; index < directDescendants.length; index++) {
  16468. var child = directDescendants[index];
  16469. if (child.clone) {
  16470. child.clone(name + "." + child.name, result);
  16471. }
  16472. }
  16473. }
  16474. return result;
  16475. };
  16476. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16477. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16478. serializationObject.type = this.getClassName();
  16479. // Parent
  16480. if (this.parent) {
  16481. serializationObject.parentId = this.parent.id;
  16482. }
  16483. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16484. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16485. }
  16486. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16487. serializationObject.isEnabled = this.isEnabled();
  16488. // Parent
  16489. if (this.parent) {
  16490. serializationObject.parentId = this.parent.id;
  16491. }
  16492. return serializationObject;
  16493. };
  16494. // Statics
  16495. /**
  16496. * Returns a new TransformNode object parsed from the source provided.
  16497. * The parameter `parsedMesh` is the source.
  16498. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16499. */
  16500. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16501. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16502. if (BABYLON.Tags) {
  16503. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16504. }
  16505. if (parsedTransformNode.localMatrix) {
  16506. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16507. }
  16508. else if (parsedTransformNode.pivotMatrix) {
  16509. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16510. }
  16511. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16512. // Parent
  16513. if (parsedTransformNode.parentId) {
  16514. transformNode._waitingParentId = parsedTransformNode.parentId;
  16515. }
  16516. return transformNode;
  16517. };
  16518. /**
  16519. * Disposes the TransformNode.
  16520. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16521. * Returns nothing.
  16522. */
  16523. TransformNode.prototype.dispose = function (doNotRecurse) {
  16524. // Animations
  16525. this.getScene().stopAnimation(this);
  16526. // Remove from scene
  16527. this.getScene().removeTransformNode(this);
  16528. if (!doNotRecurse) {
  16529. // Children
  16530. var objects = this.getDescendants(true);
  16531. for (var index = 0; index < objects.length; index++) {
  16532. objects[index].dispose();
  16533. }
  16534. }
  16535. else {
  16536. var childMeshes = this.getChildMeshes(true);
  16537. for (index = 0; index < childMeshes.length; index++) {
  16538. var child = childMeshes[index];
  16539. child.parent = null;
  16540. child.computeWorldMatrix(true);
  16541. }
  16542. }
  16543. this.onAfterWorldMatrixUpdateObservable.clear();
  16544. _super.prototype.dispose.call(this);
  16545. };
  16546. // Statics
  16547. TransformNode.BILLBOARDMODE_NONE = 0;
  16548. TransformNode.BILLBOARDMODE_X = 1;
  16549. TransformNode.BILLBOARDMODE_Y = 2;
  16550. TransformNode.BILLBOARDMODE_Z = 4;
  16551. TransformNode.BILLBOARDMODE_ALL = 7;
  16552. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16553. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16554. __decorate([
  16555. BABYLON.serializeAsVector3()
  16556. ], TransformNode.prototype, "_rotation", void 0);
  16557. __decorate([
  16558. BABYLON.serializeAsQuaternion()
  16559. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16560. __decorate([
  16561. BABYLON.serializeAsVector3()
  16562. ], TransformNode.prototype, "_scaling", void 0);
  16563. __decorate([
  16564. BABYLON.serialize()
  16565. ], TransformNode.prototype, "billboardMode", void 0);
  16566. __decorate([
  16567. BABYLON.serialize()
  16568. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16569. __decorate([
  16570. BABYLON.serialize()
  16571. ], TransformNode.prototype, "infiniteDistance", void 0);
  16572. __decorate([
  16573. BABYLON.serializeAsVector3()
  16574. ], TransformNode.prototype, "position", void 0);
  16575. return TransformNode;
  16576. }(BABYLON.Node));
  16577. BABYLON.TransformNode = TransformNode;
  16578. })(BABYLON || (BABYLON = {}));
  16579. //# sourceMappingURL=babylon.transformNode.js.map
  16580. var BABYLON;
  16581. (function (BABYLON) {
  16582. var AbstractMesh = /** @class */ (function (_super) {
  16583. __extends(AbstractMesh, _super);
  16584. // Constructor
  16585. function AbstractMesh(name, scene) {
  16586. if (scene === void 0) { scene = null; }
  16587. var _this = _super.call(this, name, scene, false) || this;
  16588. _this._facetNb = 0; // facet number
  16589. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16590. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16591. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16592. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16593. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16594. _this._subDiv = {
  16595. max: 1,
  16596. X: 1,
  16597. Y: 1,
  16598. Z: 1
  16599. };
  16600. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16601. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16602. // Events
  16603. /**
  16604. * An event triggered when this mesh collides with another one
  16605. * @type {BABYLON.Observable}
  16606. */
  16607. _this.onCollideObservable = new BABYLON.Observable();
  16608. /**
  16609. * An event triggered when the collision's position changes
  16610. * @type {BABYLON.Observable}
  16611. */
  16612. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16613. /**
  16614. * An event triggered when material is changed
  16615. * @type {BABYLON.Observable}
  16616. */
  16617. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16618. // Properties
  16619. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16620. /**
  16621. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16622. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16623. * or
  16624. * 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.
  16625. * for more info check WebGl documentations
  16626. */
  16627. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16628. /**
  16629. * 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:
  16630. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16631. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16632. * 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.
  16633. */
  16634. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16635. /**
  16636. * 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.
  16637. * The default value is -1 which means don't break the query and wait till the result.
  16638. */
  16639. _this.occlusionRetryCount = -1;
  16640. _this._occlusionInternalRetryCounter = 0;
  16641. _this._isOccluded = false;
  16642. _this._isOcclusionQueryInProgress = false;
  16643. _this._visibility = 1.0;
  16644. _this.alphaIndex = Number.MAX_VALUE;
  16645. _this.isVisible = true;
  16646. _this.isPickable = true;
  16647. _this.showBoundingBox = false;
  16648. _this.showSubMeshesBoundingBox = false;
  16649. _this.isBlocker = false;
  16650. _this.enablePointerMoveEvents = false;
  16651. _this.renderingGroupId = 0;
  16652. _this._receiveShadows = false;
  16653. _this.renderOutline = false;
  16654. _this.outlineColor = BABYLON.Color3.Red();
  16655. _this.outlineWidth = 0.02;
  16656. _this.renderOverlay = false;
  16657. _this.overlayColor = BABYLON.Color3.Red();
  16658. _this.overlayAlpha = 0.5;
  16659. _this._hasVertexAlpha = false;
  16660. _this._useVertexColors = true;
  16661. _this._computeBonesUsingShaders = true;
  16662. _this._numBoneInfluencers = 4;
  16663. _this._applyFog = true;
  16664. _this.useOctreeForRenderingSelection = true;
  16665. _this.useOctreeForPicking = true;
  16666. _this.useOctreeForCollisions = true;
  16667. _this._layerMask = 0x0FFFFFFF;
  16668. /**
  16669. * True if the mesh must be rendered in any case.
  16670. */
  16671. _this.alwaysSelectAsActiveMesh = false;
  16672. /**
  16673. * This scene's action manager
  16674. * @type {BABYLON.ActionManager}
  16675. */
  16676. _this.actionManager = null;
  16677. // Physics
  16678. _this.physicsImpostor = null;
  16679. // Collisions
  16680. _this._checkCollisions = false;
  16681. _this._collisionMask = -1;
  16682. _this._collisionGroup = -1;
  16683. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16684. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16685. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16686. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16687. // Edges
  16688. _this.edgesWidth = 1;
  16689. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16690. // Cache
  16691. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16692. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16693. _this._isDisposed = false;
  16694. _this._renderId = 0;
  16695. _this._intersectionsInProgress = new Array();
  16696. _this._unIndexed = false;
  16697. _this._lightSources = new Array();
  16698. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16699. if (collidedMesh === void 0) { collidedMesh = null; }
  16700. //TODO move this to the collision coordinator!
  16701. if (_this.getScene().workerCollisions)
  16702. newPosition.multiplyInPlace(_this._collider._radius);
  16703. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16704. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16705. _this.position.addInPlace(_this._diffPositionForCollisions);
  16706. }
  16707. if (collidedMesh) {
  16708. _this.onCollideObservable.notifyObservers(collidedMesh);
  16709. }
  16710. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16711. };
  16712. _this.getScene().addMesh(_this);
  16713. _this._resyncLightSources();
  16714. return _this;
  16715. }
  16716. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16717. get: function () {
  16718. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16724. get: function () {
  16725. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16726. },
  16727. enumerable: true,
  16728. configurable: true
  16729. });
  16730. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16731. get: function () {
  16732. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16733. },
  16734. enumerable: true,
  16735. configurable: true
  16736. });
  16737. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16738. get: function () {
  16739. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16745. get: function () {
  16746. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16747. },
  16748. enumerable: true,
  16749. configurable: true
  16750. });
  16751. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16752. /**
  16753. * Read-only : the number of facets in the mesh
  16754. */
  16755. get: function () {
  16756. return this._facetNb;
  16757. },
  16758. enumerable: true,
  16759. configurable: true
  16760. });
  16761. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16762. /**
  16763. * The number (integer) of subdivisions per axis in the partioning space
  16764. */
  16765. get: function () {
  16766. return this._partitioningSubdivisions;
  16767. },
  16768. set: function (nb) {
  16769. this._partitioningSubdivisions = nb;
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16775. /**
  16776. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16777. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16778. */
  16779. get: function () {
  16780. return this._partitioningBBoxRatio;
  16781. },
  16782. set: function (ratio) {
  16783. this._partitioningBBoxRatio = ratio;
  16784. },
  16785. enumerable: true,
  16786. configurable: true
  16787. });
  16788. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16789. /**
  16790. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16791. * Works only for updatable meshes.
  16792. * Doesn't work with multi-materials.
  16793. */
  16794. get: function () {
  16795. return this._facetDepthSort;
  16796. },
  16797. set: function (sort) {
  16798. this._facetDepthSort = sort;
  16799. },
  16800. enumerable: true,
  16801. configurable: true
  16802. });
  16803. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16804. /**
  16805. * The location (Vector3) where the facet depth sort must be computed from.
  16806. * By default, the active camera position.
  16807. * Used only when facet depth sort is enabled.
  16808. */
  16809. get: function () {
  16810. return this._facetDepthSortFrom;
  16811. },
  16812. set: function (location) {
  16813. this._facetDepthSortFrom = location;
  16814. },
  16815. enumerable: true,
  16816. configurable: true
  16817. });
  16818. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16819. /**
  16820. * Read-only boolean : is the feature facetData enabled ?
  16821. */
  16822. get: function () {
  16823. return this._facetDataEnabled;
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16829. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16830. return false;
  16831. }
  16832. this._markSubMeshesAsMiscDirty();
  16833. return true;
  16834. };
  16835. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16836. set: function (callback) {
  16837. if (this._onCollideObserver) {
  16838. this.onCollideObservable.remove(this._onCollideObserver);
  16839. }
  16840. this._onCollideObserver = this.onCollideObservable.add(callback);
  16841. },
  16842. enumerable: true,
  16843. configurable: true
  16844. });
  16845. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16846. set: function (callback) {
  16847. if (this._onCollisionPositionChangeObserver) {
  16848. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16849. }
  16850. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16856. /**
  16857. * 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.
  16858. */
  16859. get: function () {
  16860. return this._isOccluded;
  16861. },
  16862. set: function (value) {
  16863. this._isOccluded = value;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16869. /**
  16870. * Flag to check the progress status of the query
  16871. */
  16872. get: function () {
  16873. return this._isOcclusionQueryInProgress;
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16879. /**
  16880. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16881. */
  16882. get: function () {
  16883. return this._visibility;
  16884. },
  16885. /**
  16886. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16887. */
  16888. set: function (value) {
  16889. if (this._visibility === value) {
  16890. return;
  16891. }
  16892. this._visibility = value;
  16893. this._markSubMeshesAsMiscDirty();
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(AbstractMesh.prototype, "material", {
  16899. get: function () {
  16900. return this._material;
  16901. },
  16902. set: function (value) {
  16903. if (this._material === value) {
  16904. return;
  16905. }
  16906. this._material = value;
  16907. if (this.onMaterialChangedObservable.hasObservers) {
  16908. this.onMaterialChangedObservable.notifyObservers(this);
  16909. }
  16910. if (!this.subMeshes) {
  16911. return;
  16912. }
  16913. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16914. var subMesh = _a[_i];
  16915. subMesh.setEffect(null);
  16916. }
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16922. get: function () {
  16923. return this._receiveShadows;
  16924. },
  16925. set: function (value) {
  16926. if (this._receiveShadows === value) {
  16927. return;
  16928. }
  16929. this._receiveShadows = value;
  16930. this._markSubMeshesAsLightDirty();
  16931. },
  16932. enumerable: true,
  16933. configurable: true
  16934. });
  16935. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16936. get: function () {
  16937. return this._hasVertexAlpha;
  16938. },
  16939. set: function (value) {
  16940. if (this._hasVertexAlpha === value) {
  16941. return;
  16942. }
  16943. this._hasVertexAlpha = value;
  16944. this._markSubMeshesAsAttributesDirty();
  16945. this._markSubMeshesAsMiscDirty();
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16951. get: function () {
  16952. return this._useVertexColors;
  16953. },
  16954. set: function (value) {
  16955. if (this._useVertexColors === value) {
  16956. return;
  16957. }
  16958. this._useVertexColors = value;
  16959. this._markSubMeshesAsAttributesDirty();
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16965. get: function () {
  16966. return this._computeBonesUsingShaders;
  16967. },
  16968. set: function (value) {
  16969. if (this._computeBonesUsingShaders === value) {
  16970. return;
  16971. }
  16972. this._computeBonesUsingShaders = value;
  16973. this._markSubMeshesAsAttributesDirty();
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16979. get: function () {
  16980. return this._numBoneInfluencers;
  16981. },
  16982. set: function (value) {
  16983. if (this._numBoneInfluencers === value) {
  16984. return;
  16985. }
  16986. this._numBoneInfluencers = value;
  16987. this._markSubMeshesAsAttributesDirty();
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16993. get: function () {
  16994. return this._applyFog;
  16995. },
  16996. set: function (value) {
  16997. if (this._applyFog === value) {
  16998. return;
  16999. }
  17000. this._applyFog = value;
  17001. this._markSubMeshesAsMiscDirty();
  17002. },
  17003. enumerable: true,
  17004. configurable: true
  17005. });
  17006. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17007. get: function () {
  17008. return this._layerMask;
  17009. },
  17010. set: function (value) {
  17011. if (value === this._layerMask) {
  17012. return;
  17013. }
  17014. this._layerMask = value;
  17015. this._resyncLightSources();
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17021. get: function () {
  17022. return this._collisionMask;
  17023. },
  17024. set: function (mask) {
  17025. this._collisionMask = !isNaN(mask) ? mask : -1;
  17026. },
  17027. enumerable: true,
  17028. configurable: true
  17029. });
  17030. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17031. get: function () {
  17032. return this._collisionGroup;
  17033. },
  17034. set: function (mask) {
  17035. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17036. },
  17037. enumerable: true,
  17038. configurable: true
  17039. });
  17040. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17041. get: function () {
  17042. return null;
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17048. get: function () {
  17049. return this._skeleton;
  17050. },
  17051. set: function (value) {
  17052. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17053. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17054. }
  17055. if (value && value.needInitialSkinMatrix) {
  17056. value._registerMeshWithPoseMatrix(this);
  17057. }
  17058. this._skeleton = value;
  17059. if (!this._skeleton) {
  17060. this._bonesTransformMatrices = null;
  17061. }
  17062. this._markSubMeshesAsAttributesDirty();
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. /**
  17068. * Boolean : true if the mesh has been disposed.
  17069. */
  17070. AbstractMesh.prototype.isDisposed = function () {
  17071. return this._isDisposed;
  17072. };
  17073. /**
  17074. * Returns the string "AbstractMesh"
  17075. */
  17076. AbstractMesh.prototype.getClassName = function () {
  17077. return "AbstractMesh";
  17078. };
  17079. /**
  17080. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17081. */
  17082. AbstractMesh.prototype.toString = function (fullDetails) {
  17083. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17084. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17085. if (this._skeleton) {
  17086. ret += ", skeleton: " + this._skeleton.name;
  17087. }
  17088. if (fullDetails) {
  17089. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17090. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17091. }
  17092. return ret;
  17093. };
  17094. AbstractMesh.prototype._rebuild = function () {
  17095. if (this._occlusionQuery) {
  17096. this._occlusionQuery = null;
  17097. }
  17098. if (this._edgesRenderer) {
  17099. this._edgesRenderer._rebuild();
  17100. }
  17101. if (!this.subMeshes) {
  17102. return;
  17103. }
  17104. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17105. var subMesh = _a[_i];
  17106. subMesh._rebuild();
  17107. }
  17108. };
  17109. AbstractMesh.prototype._resyncLightSources = function () {
  17110. this._lightSources.length = 0;
  17111. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17112. var light = _a[_i];
  17113. if (!light.isEnabled()) {
  17114. continue;
  17115. }
  17116. if (light.canAffectMesh(this)) {
  17117. this._lightSources.push(light);
  17118. }
  17119. }
  17120. this._markSubMeshesAsLightDirty();
  17121. };
  17122. AbstractMesh.prototype._resyncLighSource = function (light) {
  17123. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17124. var index = this._lightSources.indexOf(light);
  17125. if (index === -1) {
  17126. if (!isIn) {
  17127. return;
  17128. }
  17129. this._lightSources.push(light);
  17130. }
  17131. else {
  17132. if (isIn) {
  17133. return;
  17134. }
  17135. this._lightSources.splice(index, 1);
  17136. }
  17137. this._markSubMeshesAsLightDirty();
  17138. };
  17139. AbstractMesh.prototype._removeLightSource = function (light) {
  17140. var index = this._lightSources.indexOf(light);
  17141. if (index === -1) {
  17142. return;
  17143. }
  17144. this._lightSources.splice(index, 1);
  17145. this._markSubMeshesAsLightDirty();
  17146. };
  17147. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17148. if (!this.subMeshes) {
  17149. return;
  17150. }
  17151. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17152. var subMesh = _a[_i];
  17153. if (subMesh._materialDefines) {
  17154. func(subMesh._materialDefines);
  17155. }
  17156. }
  17157. };
  17158. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17159. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17160. };
  17161. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17162. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17163. };
  17164. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17165. if (!this.subMeshes) {
  17166. return;
  17167. }
  17168. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17169. var subMesh = _a[_i];
  17170. var material = subMesh.getMaterial();
  17171. if (material) {
  17172. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17173. }
  17174. }
  17175. };
  17176. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17177. /**
  17178. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17179. * Default : (1.0, 1.0, 1.0)
  17180. */
  17181. get: function () {
  17182. return this._scaling;
  17183. },
  17184. /**
  17185. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17186. * Default : (1.0, 1.0, 1.0)
  17187. */
  17188. set: function (newScaling) {
  17189. this._scaling = newScaling;
  17190. if (this.physicsImpostor) {
  17191. this.physicsImpostor.forceUpdate();
  17192. }
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. // Methods
  17198. /**
  17199. * Disables the mesh edger rendering mode.
  17200. * Returns the AbstractMesh.
  17201. */
  17202. AbstractMesh.prototype.disableEdgesRendering = function () {
  17203. if (this._edgesRenderer) {
  17204. this._edgesRenderer.dispose();
  17205. this._edgesRenderer = null;
  17206. }
  17207. return this;
  17208. };
  17209. /**
  17210. * Enables the edge rendering mode on the mesh.
  17211. * This mode makes the mesh edges visible.
  17212. * Returns the AbstractMesh.
  17213. */
  17214. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17215. if (epsilon === void 0) { epsilon = 0.95; }
  17216. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17217. this.disableEdgesRendering();
  17218. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17219. return this;
  17220. };
  17221. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17222. /**
  17223. * Returns true if the mesh is blocked. Used by the class Mesh.
  17224. * Returns the boolean `false` by default.
  17225. */
  17226. get: function () {
  17227. return false;
  17228. },
  17229. enumerable: true,
  17230. configurable: true
  17231. });
  17232. /**
  17233. * Returns the mesh itself by default, used by the class Mesh.
  17234. * Returned type : AbstractMesh
  17235. */
  17236. AbstractMesh.prototype.getLOD = function (camera) {
  17237. return this;
  17238. };
  17239. /**
  17240. * Returns 0 by default, used by the class Mesh.
  17241. * Returns an integer.
  17242. */
  17243. AbstractMesh.prototype.getTotalVertices = function () {
  17244. return 0;
  17245. };
  17246. /**
  17247. * Returns null by default, used by the class Mesh.
  17248. * Returned type : integer array
  17249. */
  17250. AbstractMesh.prototype.getIndices = function () {
  17251. return null;
  17252. };
  17253. /**
  17254. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17255. * Returned type : float array or Float32Array
  17256. */
  17257. AbstractMesh.prototype.getVerticesData = function (kind) {
  17258. return null;
  17259. };
  17260. /**
  17261. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17262. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17263. * The `data` are either a numeric array either a Float32Array.
  17264. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17265. * 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).
  17266. * Note that a new underlying VertexBuffer object is created each call.
  17267. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17268. *
  17269. * Possible `kind` values :
  17270. * - BABYLON.VertexBuffer.PositionKind
  17271. * - BABYLON.VertexBuffer.UVKind
  17272. * - BABYLON.VertexBuffer.UV2Kind
  17273. * - BABYLON.VertexBuffer.UV3Kind
  17274. * - BABYLON.VertexBuffer.UV4Kind
  17275. * - BABYLON.VertexBuffer.UV5Kind
  17276. * - BABYLON.VertexBuffer.UV6Kind
  17277. * - BABYLON.VertexBuffer.ColorKind
  17278. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17279. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17280. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17281. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17282. *
  17283. * Returns the Mesh.
  17284. */
  17285. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17286. return this;
  17287. };
  17288. /**
  17289. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17290. * If the mesh has no geometry, it is simply returned as it is.
  17291. * The `data` are either a numeric array either a Float32Array.
  17292. * No new underlying VertexBuffer object is created.
  17293. * 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.
  17294. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17295. *
  17296. * Possible `kind` values :
  17297. * - BABYLON.VertexBuffer.PositionKind
  17298. * - BABYLON.VertexBuffer.UVKind
  17299. * - BABYLON.VertexBuffer.UV2Kind
  17300. * - BABYLON.VertexBuffer.UV3Kind
  17301. * - BABYLON.VertexBuffer.UV4Kind
  17302. * - BABYLON.VertexBuffer.UV5Kind
  17303. * - BABYLON.VertexBuffer.UV6Kind
  17304. * - BABYLON.VertexBuffer.ColorKind
  17305. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17306. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17307. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17308. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17309. *
  17310. * Returns the Mesh.
  17311. */
  17312. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17313. return this;
  17314. };
  17315. /**
  17316. * Sets the mesh indices.
  17317. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17318. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17319. * This method creates a new index buffer each call.
  17320. * Returns the Mesh.
  17321. */
  17322. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17323. return this;
  17324. };
  17325. /** Returns false by default, used by the class Mesh.
  17326. * Returns a boolean
  17327. */
  17328. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17329. return false;
  17330. };
  17331. /**
  17332. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17333. * Returns a BoundingInfo
  17334. */
  17335. AbstractMesh.prototype.getBoundingInfo = function () {
  17336. if (this._masterMesh) {
  17337. return this._masterMesh.getBoundingInfo();
  17338. }
  17339. if (!this._boundingInfo) {
  17340. // this._boundingInfo is being created here
  17341. this._updateBoundingInfo();
  17342. }
  17343. // cannot be null.
  17344. return this._boundingInfo;
  17345. };
  17346. /**
  17347. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17348. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17349. */
  17350. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17351. if (includeDescendants === void 0) { includeDescendants = true; }
  17352. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17353. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17354. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17355. if (maxDimension === 0) {
  17356. return this;
  17357. }
  17358. var scale = 1 / maxDimension;
  17359. this.scaling.scaleInPlace(scale);
  17360. return this;
  17361. };
  17362. /**
  17363. * Sets a mesh new object BoundingInfo.
  17364. * Returns the AbstractMesh.
  17365. */
  17366. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17367. this._boundingInfo = boundingInfo;
  17368. return this;
  17369. };
  17370. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17371. get: function () {
  17372. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17373. },
  17374. enumerable: true,
  17375. configurable: true
  17376. });
  17377. AbstractMesh.prototype._preActivate = function () {
  17378. };
  17379. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17380. };
  17381. AbstractMesh.prototype._activate = function (renderId) {
  17382. this._renderId = renderId;
  17383. };
  17384. /**
  17385. * Returns the latest update of the World matrix
  17386. * Returns a Matrix.
  17387. */
  17388. AbstractMesh.prototype.getWorldMatrix = function () {
  17389. if (this._masterMesh) {
  17390. return this._masterMesh.getWorldMatrix();
  17391. }
  17392. return _super.prototype.getWorldMatrix.call(this);
  17393. };
  17394. /**
  17395. * Returns the latest update of the World matrix determinant.
  17396. */
  17397. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17398. if (this._masterMesh) {
  17399. return this._masterMesh._getWorldMatrixDeterminant();
  17400. }
  17401. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17402. };
  17403. // ================================== Point of View Movement =================================
  17404. /**
  17405. * Perform relative position change from the point of view of behind the front of the mesh.
  17406. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17407. * Supports definition of mesh facing forward or backward.
  17408. * @param {number} amountRight
  17409. * @param {number} amountUp
  17410. * @param {number} amountForward
  17411. *
  17412. * Returns the AbstractMesh.
  17413. */
  17414. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17415. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17416. return this;
  17417. };
  17418. /**
  17419. * Calculate relative position change from the point of view of behind the front of the mesh.
  17420. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17421. * Supports definition of mesh facing forward or backward.
  17422. * @param {number} amountRight
  17423. * @param {number} amountUp
  17424. * @param {number} amountForward
  17425. *
  17426. * Returns a new Vector3.
  17427. */
  17428. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17429. var rotMatrix = new BABYLON.Matrix();
  17430. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17431. rotQuaternion.toRotationMatrix(rotMatrix);
  17432. var translationDelta = BABYLON.Vector3.Zero();
  17433. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17434. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17435. return translationDelta;
  17436. };
  17437. // ================================== Point of View Rotation =================================
  17438. /**
  17439. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17440. * Supports definition of mesh facing forward or backward.
  17441. * @param {number} flipBack
  17442. * @param {number} twirlClockwise
  17443. * @param {number} tiltRight
  17444. *
  17445. * Returns the AbstractMesh.
  17446. */
  17447. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17448. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17449. return this;
  17450. };
  17451. /**
  17452. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17453. * Supports definition of mesh facing forward or backward.
  17454. * @param {number} flipBack
  17455. * @param {number} twirlClockwise
  17456. * @param {number} tiltRight
  17457. *
  17458. * Returns a new Vector3.
  17459. */
  17460. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17461. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17462. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17463. };
  17464. /**
  17465. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17466. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17467. */
  17468. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17469. if (includeDescendants === void 0) { includeDescendants = true; }
  17470. this.computeWorldMatrix(true);
  17471. var min;
  17472. var max;
  17473. var boundingInfo = this.getBoundingInfo();
  17474. if (!this.subMeshes) {
  17475. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17476. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17477. }
  17478. else {
  17479. min = boundingInfo.boundingBox.minimumWorld;
  17480. max = boundingInfo.boundingBox.maximumWorld;
  17481. }
  17482. if (includeDescendants) {
  17483. var descendants = this.getDescendants(false);
  17484. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17485. var descendant = descendants_1[_i];
  17486. var childMesh = descendant;
  17487. childMesh.computeWorldMatrix(true);
  17488. //make sure we have the needed params to get mix and max
  17489. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17490. continue;
  17491. }
  17492. var childBoundingInfo = childMesh.getBoundingInfo();
  17493. var boundingBox = childBoundingInfo.boundingBox;
  17494. var minBox = boundingBox.minimumWorld;
  17495. var maxBox = boundingBox.maximumWorld;
  17496. BABYLON.Tools.CheckExtends(minBox, min, max);
  17497. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17498. }
  17499. }
  17500. return {
  17501. min: min,
  17502. max: max
  17503. };
  17504. };
  17505. /**
  17506. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17507. * Returns the AbstractMesh.
  17508. */
  17509. AbstractMesh.prototype._updateBoundingInfo = function () {
  17510. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17511. this._boundingInfo.update(this.worldMatrixFromCache);
  17512. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17513. return this;
  17514. };
  17515. /**
  17516. * Update a mesh's children BoundingInfo objects only.
  17517. * Returns the AbstractMesh.
  17518. */
  17519. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17520. if (!this.subMeshes) {
  17521. return this;
  17522. }
  17523. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17524. var subMesh = this.subMeshes[subIndex];
  17525. if (!subMesh.IsGlobal) {
  17526. subMesh.updateBoundingInfo(matrix);
  17527. }
  17528. }
  17529. return this;
  17530. };
  17531. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17532. // Bounding info
  17533. this._updateBoundingInfo();
  17534. };
  17535. /**
  17536. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17537. * A mesh is in the frustum if its bounding box intersects the frustum.
  17538. * Boolean returned.
  17539. */
  17540. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17541. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17542. };
  17543. /**
  17544. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17545. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17546. * Boolean returned.
  17547. */
  17548. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17549. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17550. ;
  17551. };
  17552. /**
  17553. * True if the mesh intersects another mesh or a SolidParticle object.
  17554. * 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)
  17555. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17556. * Returns a boolean.
  17557. */
  17558. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17559. if (precise === void 0) { precise = false; }
  17560. if (!this._boundingInfo || !mesh._boundingInfo) {
  17561. return false;
  17562. }
  17563. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17564. return true;
  17565. }
  17566. if (includeDescendants) {
  17567. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17568. var child = _a[_i];
  17569. if (child.intersectsMesh(mesh, precise, true)) {
  17570. return true;
  17571. }
  17572. }
  17573. }
  17574. return false;
  17575. };
  17576. /**
  17577. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17578. * Returns a boolean.
  17579. */
  17580. AbstractMesh.prototype.intersectsPoint = function (point) {
  17581. if (!this._boundingInfo) {
  17582. return false;
  17583. }
  17584. return this._boundingInfo.intersectsPoint(point);
  17585. };
  17586. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17587. return this.physicsImpostor;
  17588. };
  17589. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17590. if (camera === void 0) { camera = null; }
  17591. if (!camera) {
  17592. camera = this.getScene().activeCamera;
  17593. }
  17594. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17595. };
  17596. /**
  17597. * Returns the distance from the mesh to the active camera.
  17598. * Returns a float.
  17599. */
  17600. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17601. if (camera === void 0) { camera = null; }
  17602. if (!camera) {
  17603. camera = this.getScene().activeCamera;
  17604. }
  17605. return this.absolutePosition.subtract(camera.position).length();
  17606. };
  17607. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17608. if (!this.physicsImpostor) {
  17609. return this;
  17610. }
  17611. this.physicsImpostor.applyImpulse(force, contactPoint);
  17612. return this;
  17613. };
  17614. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17615. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17616. return this;
  17617. }
  17618. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17619. mainPivot: pivot1,
  17620. connectedPivot: pivot2,
  17621. nativeParams: options
  17622. });
  17623. return this;
  17624. };
  17625. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17626. // Collisions
  17627. /**
  17628. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17629. * Default `false`.
  17630. */
  17631. get: function () {
  17632. return this._checkCollisions;
  17633. },
  17634. set: function (collisionEnabled) {
  17635. this._checkCollisions = collisionEnabled;
  17636. if (this.getScene().workerCollisions) {
  17637. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17638. }
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17644. /**
  17645. * Gets Collider object used to compute collisions (not physics)
  17646. */
  17647. get: function () {
  17648. return this._collider;
  17649. },
  17650. enumerable: true,
  17651. configurable: true
  17652. });
  17653. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17654. var globalPosition = this.getAbsolutePosition();
  17655. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17656. if (!this._collider) {
  17657. this._collider = new BABYLON.Collider();
  17658. }
  17659. this._collider._radius = this.ellipsoid;
  17660. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17661. return this;
  17662. };
  17663. // Submeshes octree
  17664. /**
  17665. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17666. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17667. * Returns an Octree of submeshes.
  17668. */
  17669. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17670. if (maxCapacity === void 0) { maxCapacity = 64; }
  17671. if (maxDepth === void 0) { maxDepth = 2; }
  17672. if (!this._submeshesOctree) {
  17673. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17674. }
  17675. this.computeWorldMatrix(true);
  17676. var boundingInfo = this.getBoundingInfo();
  17677. // Update octree
  17678. var bbox = boundingInfo.boundingBox;
  17679. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17680. return this._submeshesOctree;
  17681. };
  17682. // Collisions
  17683. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17684. this._generatePointsArray();
  17685. if (!this._positions) {
  17686. return this;
  17687. }
  17688. // Transformation
  17689. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17690. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17691. subMesh._lastColliderWorldVertices = [];
  17692. subMesh._trianglePlanes = [];
  17693. var start = subMesh.verticesStart;
  17694. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17695. for (var i = start; i < end; i++) {
  17696. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17697. }
  17698. }
  17699. // Collide
  17700. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17701. if (collider.collisionFound) {
  17702. collider.collidedMesh = this;
  17703. }
  17704. return this;
  17705. };
  17706. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17707. var subMeshes;
  17708. var len;
  17709. // Octrees
  17710. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17711. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17712. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17713. len = intersections.length;
  17714. subMeshes = intersections.data;
  17715. }
  17716. else {
  17717. subMeshes = this.subMeshes;
  17718. len = subMeshes.length;
  17719. }
  17720. for (var index = 0; index < len; index++) {
  17721. var subMesh = subMeshes[index];
  17722. // Bounding test
  17723. if (len > 1 && !subMesh._checkCollision(collider))
  17724. continue;
  17725. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17726. }
  17727. return this;
  17728. };
  17729. AbstractMesh.prototype._checkCollision = function (collider) {
  17730. // Bounding box test
  17731. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17732. return this;
  17733. // Transformation matrix
  17734. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17735. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17736. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17737. return this;
  17738. };
  17739. // Picking
  17740. AbstractMesh.prototype._generatePointsArray = function () {
  17741. return false;
  17742. };
  17743. /**
  17744. * Checks if the passed Ray intersects with the mesh.
  17745. * Returns an object PickingInfo.
  17746. */
  17747. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17748. var pickingInfo = new BABYLON.PickingInfo();
  17749. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17750. return pickingInfo;
  17751. }
  17752. if (!this._generatePointsArray()) {
  17753. return pickingInfo;
  17754. }
  17755. var intersectInfo = null;
  17756. // Octrees
  17757. var subMeshes;
  17758. var len;
  17759. if (this._submeshesOctree && this.useOctreeForPicking) {
  17760. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17761. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17762. len = intersections.length;
  17763. subMeshes = intersections.data;
  17764. }
  17765. else {
  17766. subMeshes = this.subMeshes;
  17767. len = subMeshes.length;
  17768. }
  17769. for (var index = 0; index < len; index++) {
  17770. var subMesh = subMeshes[index];
  17771. // Bounding test
  17772. if (len > 1 && !subMesh.canIntersects(ray))
  17773. continue;
  17774. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17775. if (currentIntersectInfo) {
  17776. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17777. intersectInfo = currentIntersectInfo;
  17778. intersectInfo.subMeshId = index;
  17779. if (fastCheck) {
  17780. break;
  17781. }
  17782. }
  17783. }
  17784. }
  17785. if (intersectInfo) {
  17786. // Get picked point
  17787. var world = this.getWorldMatrix();
  17788. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17789. var direction = ray.direction.clone();
  17790. direction = direction.scale(intersectInfo.distance);
  17791. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17792. var pickedPoint = worldOrigin.add(worldDirection);
  17793. // Return result
  17794. pickingInfo.hit = true;
  17795. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17796. pickingInfo.pickedPoint = pickedPoint;
  17797. pickingInfo.pickedMesh = this;
  17798. pickingInfo.bu = intersectInfo.bu || 0;
  17799. pickingInfo.bv = intersectInfo.bv || 0;
  17800. pickingInfo.faceId = intersectInfo.faceId;
  17801. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17802. return pickingInfo;
  17803. }
  17804. return pickingInfo;
  17805. };
  17806. /**
  17807. * Clones the mesh, used by the class Mesh.
  17808. * Just returns `null` for an AbstractMesh.
  17809. */
  17810. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17811. return null;
  17812. };
  17813. /**
  17814. * Disposes all the mesh submeshes.
  17815. * Returns the AbstractMesh.
  17816. */
  17817. AbstractMesh.prototype.releaseSubMeshes = function () {
  17818. if (this.subMeshes) {
  17819. while (this.subMeshes.length) {
  17820. this.subMeshes[0].dispose();
  17821. }
  17822. }
  17823. else {
  17824. this.subMeshes = new Array();
  17825. }
  17826. return this;
  17827. };
  17828. /**
  17829. * Disposes the AbstractMesh.
  17830. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17831. * Returns nothing.
  17832. */
  17833. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17834. var _this = this;
  17835. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17836. var index;
  17837. // Action manager
  17838. if (this.actionManager !== undefined && this.actionManager !== null) {
  17839. this.actionManager.dispose();
  17840. this.actionManager = null;
  17841. }
  17842. // Skeleton
  17843. this.skeleton = null;
  17844. // Physics
  17845. if (this.physicsImpostor) {
  17846. this.physicsImpostor.dispose();
  17847. }
  17848. // Intersections in progress
  17849. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17850. var other = this._intersectionsInProgress[index];
  17851. var pos = other._intersectionsInProgress.indexOf(this);
  17852. other._intersectionsInProgress.splice(pos, 1);
  17853. }
  17854. this._intersectionsInProgress = [];
  17855. // Lights
  17856. var lights = this.getScene().lights;
  17857. lights.forEach(function (light) {
  17858. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17859. if (meshIndex !== -1) {
  17860. light.includedOnlyMeshes.splice(meshIndex, 1);
  17861. }
  17862. meshIndex = light.excludedMeshes.indexOf(_this);
  17863. if (meshIndex !== -1) {
  17864. light.excludedMeshes.splice(meshIndex, 1);
  17865. }
  17866. // Shadow generators
  17867. var generator = light.getShadowGenerator();
  17868. if (generator) {
  17869. var shadowMap = generator.getShadowMap();
  17870. if (shadowMap && shadowMap.renderList) {
  17871. meshIndex = shadowMap.renderList.indexOf(_this);
  17872. if (meshIndex !== -1) {
  17873. shadowMap.renderList.splice(meshIndex, 1);
  17874. }
  17875. }
  17876. }
  17877. });
  17878. // Edges
  17879. if (this._edgesRenderer) {
  17880. this._edgesRenderer.dispose();
  17881. this._edgesRenderer = null;
  17882. }
  17883. // SubMeshes
  17884. if (this.getClassName() !== "InstancedMesh") {
  17885. this.releaseSubMeshes();
  17886. }
  17887. // Octree
  17888. var sceneOctree = this.getScene().selectionOctree;
  17889. if (sceneOctree !== undefined && sceneOctree !== null) {
  17890. var index = sceneOctree.dynamicContent.indexOf(this);
  17891. if (index !== -1) {
  17892. sceneOctree.dynamicContent.splice(index, 1);
  17893. }
  17894. }
  17895. // Query
  17896. var engine = this.getScene().getEngine();
  17897. if (this._occlusionQuery) {
  17898. this._isOcclusionQueryInProgress = false;
  17899. engine.deleteQuery(this._occlusionQuery);
  17900. this._occlusionQuery = null;
  17901. }
  17902. // Engine
  17903. engine.wipeCaches();
  17904. // Remove from scene
  17905. this.getScene().removeMesh(this);
  17906. if (disposeMaterialAndTextures) {
  17907. if (this.material) {
  17908. this.material.dispose(false, true);
  17909. }
  17910. }
  17911. if (!doNotRecurse) {
  17912. // Particles
  17913. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17914. if (this.getScene().particleSystems[index].emitter === this) {
  17915. this.getScene().particleSystems[index].dispose();
  17916. index--;
  17917. }
  17918. }
  17919. }
  17920. // facet data
  17921. if (this._facetDataEnabled) {
  17922. this.disableFacetData();
  17923. }
  17924. this.onAfterWorldMatrixUpdateObservable.clear();
  17925. this.onCollideObservable.clear();
  17926. this.onCollisionPositionChangeObservable.clear();
  17927. this._isDisposed = true;
  17928. _super.prototype.dispose.call(this, doNotRecurse);
  17929. };
  17930. /**
  17931. * Adds the passed mesh as a child to the current mesh.
  17932. * Returns the AbstractMesh.
  17933. */
  17934. AbstractMesh.prototype.addChild = function (mesh) {
  17935. mesh.setParent(this);
  17936. return this;
  17937. };
  17938. /**
  17939. * Removes the passed mesh from the current mesh children list.
  17940. * Returns the AbstractMesh.
  17941. */
  17942. AbstractMesh.prototype.removeChild = function (mesh) {
  17943. mesh.setParent(null);
  17944. return this;
  17945. };
  17946. // Facet data
  17947. /**
  17948. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17949. * Returns the AbstractMesh.
  17950. */
  17951. AbstractMesh.prototype._initFacetData = function () {
  17952. if (!this._facetNormals) {
  17953. this._facetNormals = new Array();
  17954. }
  17955. if (!this._facetPositions) {
  17956. this._facetPositions = new Array();
  17957. }
  17958. if (!this._facetPartitioning) {
  17959. this._facetPartitioning = new Array();
  17960. }
  17961. this._facetNb = (this.getIndices().length / 3) | 0;
  17962. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17963. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17964. for (var f = 0; f < this._facetNb; f++) {
  17965. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17966. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17967. }
  17968. this._facetDataEnabled = true;
  17969. return this;
  17970. };
  17971. /**
  17972. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17973. * This method can be called within the render loop.
  17974. * 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.
  17975. * Returns the AbstractMesh.
  17976. */
  17977. AbstractMesh.prototype.updateFacetData = function () {
  17978. if (!this._facetDataEnabled) {
  17979. this._initFacetData();
  17980. }
  17981. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17982. var indices = this.getIndices();
  17983. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17984. var bInfo = this.getBoundingInfo();
  17985. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17986. // init arrays, matrix and sort function on first call
  17987. this._facetDepthSortEnabled = true;
  17988. if (indices instanceof Uint16Array) {
  17989. this._depthSortedIndices = new Uint16Array(indices);
  17990. }
  17991. else if (indices instanceof Uint32Array) {
  17992. this._depthSortedIndices = new Uint32Array(indices);
  17993. }
  17994. else {
  17995. var needs32bits = false;
  17996. for (var i = 0; i < indices.length; i++) {
  17997. if (indices[i] > 65535) {
  17998. needs32bits = true;
  17999. break;
  18000. }
  18001. }
  18002. if (needs32bits) {
  18003. this._depthSortedIndices = new Uint32Array(indices);
  18004. }
  18005. else {
  18006. this._depthSortedIndices = new Uint16Array(indices);
  18007. }
  18008. }
  18009. this._facetDepthSortFunction = function (f1, f2) {
  18010. return (f2.sqDistance - f1.sqDistance);
  18011. };
  18012. if (!this._facetDepthSortFrom) {
  18013. var camera = this.getScene().activeCamera;
  18014. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18015. }
  18016. this._depthSortedFacets = [];
  18017. for (var f = 0; f < this._facetNb; f++) {
  18018. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18019. this._depthSortedFacets.push(depthSortedFacet);
  18020. }
  18021. this._invertedMatrix = BABYLON.Matrix.Identity();
  18022. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18023. }
  18024. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18025. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18026. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18027. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18028. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18029. this._subDiv.max = this._partitioningSubdivisions;
  18030. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18031. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18032. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18033. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18034. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18035. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18036. // set the parameters for ComputeNormals()
  18037. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18038. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18039. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18040. this._facetParameters.bInfo = bInfo;
  18041. this._facetParameters.bbSize = this._bbSize;
  18042. this._facetParameters.subDiv = this._subDiv;
  18043. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18044. this._facetParameters.depthSort = this._facetDepthSort;
  18045. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18046. this.computeWorldMatrix(true);
  18047. this._worldMatrix.invertToRef(this._invertedMatrix);
  18048. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18049. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18050. }
  18051. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18052. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18053. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18054. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18055. var l = (this._depthSortedIndices.length / 3) | 0;
  18056. for (var f = 0; f < l; f++) {
  18057. var sind = this._depthSortedFacets[f].ind;
  18058. this._depthSortedIndices[f * 3] = indices[sind];
  18059. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18060. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18061. }
  18062. this.updateIndices(this._depthSortedIndices);
  18063. }
  18064. return this;
  18065. };
  18066. /**
  18067. * Returns the facetLocalNormals array.
  18068. * The normals are expressed in the mesh local space.
  18069. */
  18070. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18071. if (!this._facetNormals) {
  18072. this.updateFacetData();
  18073. }
  18074. return this._facetNormals;
  18075. };
  18076. /**
  18077. * Returns the facetLocalPositions array.
  18078. * The facet positions are expressed in the mesh local space.
  18079. */
  18080. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18081. if (!this._facetPositions) {
  18082. this.updateFacetData();
  18083. }
  18084. return this._facetPositions;
  18085. };
  18086. /**
  18087. * Returns the facetLocalPartioning array.
  18088. */
  18089. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18090. if (!this._facetPartitioning) {
  18091. this.updateFacetData();
  18092. }
  18093. return this._facetPartitioning;
  18094. };
  18095. /**
  18096. * Returns the i-th facet position in the world system.
  18097. * This method allocates a new Vector3 per call.
  18098. */
  18099. AbstractMesh.prototype.getFacetPosition = function (i) {
  18100. var pos = BABYLON.Vector3.Zero();
  18101. this.getFacetPositionToRef(i, pos);
  18102. return pos;
  18103. };
  18104. /**
  18105. * Sets the reference Vector3 with the i-th facet position in the world system.
  18106. * Returns the AbstractMesh.
  18107. */
  18108. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18109. var localPos = (this.getFacetLocalPositions())[i];
  18110. var world = this.getWorldMatrix();
  18111. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18112. return this;
  18113. };
  18114. /**
  18115. * Returns the i-th facet normal in the world system.
  18116. * This method allocates a new Vector3 per call.
  18117. */
  18118. AbstractMesh.prototype.getFacetNormal = function (i) {
  18119. var norm = BABYLON.Vector3.Zero();
  18120. this.getFacetNormalToRef(i, norm);
  18121. return norm;
  18122. };
  18123. /**
  18124. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18125. * Returns the AbstractMesh.
  18126. */
  18127. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18128. var localNorm = (this.getFacetLocalNormals())[i];
  18129. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18130. return this;
  18131. };
  18132. /**
  18133. * 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).
  18134. */
  18135. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18136. var bInfo = this.getBoundingInfo();
  18137. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18138. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18139. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18140. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18141. return null;
  18142. }
  18143. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18144. };
  18145. /**
  18146. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18147. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18148. * 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.
  18149. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18150. * 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.
  18151. */
  18152. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18153. if (checkFace === void 0) { checkFace = false; }
  18154. if (facing === void 0) { facing = true; }
  18155. var world = this.getWorldMatrix();
  18156. var invMat = BABYLON.Tmp.Matrix[5];
  18157. world.invertToRef(invMat);
  18158. var invVect = BABYLON.Tmp.Vector3[8];
  18159. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18160. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18161. if (projected) {
  18162. // tranform the local computed projected vector to world coordinates
  18163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18164. }
  18165. return closest;
  18166. };
  18167. /**
  18168. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18169. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18170. * 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.
  18171. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18172. * 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.
  18173. */
  18174. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18175. if (checkFace === void 0) { checkFace = false; }
  18176. if (facing === void 0) { facing = true; }
  18177. var closest = null;
  18178. var tmpx = 0.0;
  18179. var tmpy = 0.0;
  18180. var tmpz = 0.0;
  18181. var d = 0.0; // tmp dot facet normal * facet position
  18182. var t0 = 0.0;
  18183. var projx = 0.0;
  18184. var projy = 0.0;
  18185. var projz = 0.0;
  18186. // Get all the facets in the same partitioning block than (x, y, z)
  18187. var facetPositions = this.getFacetLocalPositions();
  18188. var facetNormals = this.getFacetLocalNormals();
  18189. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18190. if (!facetsInBlock) {
  18191. return null;
  18192. }
  18193. // Get the closest facet to (x, y, z)
  18194. var shortest = Number.MAX_VALUE; // init distance vars
  18195. var tmpDistance = shortest;
  18196. var fib; // current facet in the block
  18197. var norm; // current facet normal
  18198. var p0; // current facet barycenter position
  18199. // loop on all the facets in the current partitioning block
  18200. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18201. fib = facetsInBlock[idx];
  18202. norm = facetNormals[fib];
  18203. p0 = facetPositions[fib];
  18204. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18205. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18206. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18207. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18208. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18209. projx = x + norm.x * t0;
  18210. projy = y + norm.y * t0;
  18211. projz = z + norm.z * t0;
  18212. tmpx = projx - x;
  18213. tmpy = projy - y;
  18214. tmpz = projz - z;
  18215. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18216. if (tmpDistance < shortest) {
  18217. shortest = tmpDistance;
  18218. closest = fib;
  18219. if (projected) {
  18220. projected.x = projx;
  18221. projected.y = projy;
  18222. projected.z = projz;
  18223. }
  18224. }
  18225. }
  18226. }
  18227. return closest;
  18228. };
  18229. /**
  18230. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18231. */
  18232. AbstractMesh.prototype.getFacetDataParameters = function () {
  18233. return this._facetParameters;
  18234. };
  18235. /**
  18236. * Disables the feature FacetData and frees the related memory.
  18237. * Returns the AbstractMesh.
  18238. */
  18239. AbstractMesh.prototype.disableFacetData = function () {
  18240. if (this._facetDataEnabled) {
  18241. this._facetDataEnabled = false;
  18242. this._facetPositions = new Array();
  18243. this._facetNormals = new Array();
  18244. this._facetPartitioning = new Array();
  18245. this._facetParameters = null;
  18246. this._depthSortedIndices = new Uint32Array(0);
  18247. }
  18248. return this;
  18249. };
  18250. /**
  18251. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18252. * Returns the mesh.
  18253. */
  18254. AbstractMesh.prototype.updateIndices = function (indices) {
  18255. return this;
  18256. };
  18257. /**
  18258. * The mesh Geometry. Actually used by the Mesh object.
  18259. * Returns a blank geometry object.
  18260. */
  18261. /**
  18262. * Creates new normals data for the mesh.
  18263. * @param updatable.
  18264. */
  18265. AbstractMesh.prototype.createNormals = function (updatable) {
  18266. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18267. var indices = this.getIndices();
  18268. var normals;
  18269. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18270. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18271. }
  18272. else {
  18273. normals = [];
  18274. }
  18275. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18276. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18277. };
  18278. /**
  18279. * Align the mesh with a normal.
  18280. * Returns the mesh.
  18281. */
  18282. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18283. if (!upDirection) {
  18284. upDirection = BABYLON.Axis.Y;
  18285. }
  18286. var axisX = BABYLON.Tmp.Vector3[0];
  18287. var axisZ = BABYLON.Tmp.Vector3[1];
  18288. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18289. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18290. if (this.rotationQuaternion) {
  18291. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18292. }
  18293. else {
  18294. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18295. }
  18296. return this;
  18297. };
  18298. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18299. var engine = this.getEngine();
  18300. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18301. this._isOccluded = false;
  18302. return;
  18303. }
  18304. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18305. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18306. if (isOcclusionQueryAvailable) {
  18307. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18308. this._isOcclusionQueryInProgress = false;
  18309. this._occlusionInternalRetryCounter = 0;
  18310. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18311. }
  18312. else {
  18313. this._occlusionInternalRetryCounter++;
  18314. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18315. this._isOcclusionQueryInProgress = false;
  18316. this._occlusionInternalRetryCounter = 0;
  18317. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18318. // if strict continue the last state of the object.
  18319. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18320. }
  18321. else {
  18322. return;
  18323. }
  18324. }
  18325. }
  18326. var scene = this.getScene();
  18327. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18328. if (!this._occlusionQuery) {
  18329. this._occlusionQuery = engine.createQuery();
  18330. }
  18331. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18332. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18333. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18334. this._isOcclusionQueryInProgress = true;
  18335. };
  18336. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18337. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18338. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18339. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18340. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18341. return AbstractMesh;
  18342. }(BABYLON.TransformNode));
  18343. BABYLON.AbstractMesh = AbstractMesh;
  18344. })(BABYLON || (BABYLON = {}));
  18345. //# sourceMappingURL=babylon.abstractMesh.js.map
  18346. var BABYLON;
  18347. (function (BABYLON) {
  18348. /**
  18349. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18350. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18351. * 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.
  18352. */
  18353. var Light = /** @class */ (function (_super) {
  18354. __extends(Light, _super);
  18355. /**
  18356. * Creates a Light object in the scene.
  18357. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18358. * @param name The firendly name of the light
  18359. * @param scene The scene the light belongs too
  18360. */
  18361. function Light(name, scene) {
  18362. var _this = _super.call(this, name, scene) || this;
  18363. /**
  18364. * Diffuse gives the basic color to an object.
  18365. */
  18366. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18367. /**
  18368. * Specular produces a highlight color on an object.
  18369. * Note: This is note affecting PBR materials.
  18370. */
  18371. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18372. /**
  18373. * Strength of the light.
  18374. * Note: By default it is define in the framework own unit.
  18375. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18376. */
  18377. _this.intensity = 1.0;
  18378. /**
  18379. * Defines how far from the source the light is impacting in scene units.
  18380. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18381. */
  18382. _this.range = Number.MAX_VALUE;
  18383. /**
  18384. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18385. * of light.
  18386. */
  18387. _this._photometricScale = 1.0;
  18388. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18389. _this._radius = 0.00001;
  18390. /**
  18391. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18392. * exceeding the number allowed of the materials.
  18393. */
  18394. _this.renderPriority = 0;
  18395. /**
  18396. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18397. * the current shadow generator.
  18398. */
  18399. _this.shadowEnabled = true;
  18400. _this._excludeWithLayerMask = 0;
  18401. _this._includeOnlyWithLayerMask = 0;
  18402. _this._lightmapMode = 0;
  18403. /**
  18404. * @ignore Internal use only.
  18405. */
  18406. _this._excludedMeshesIds = new Array();
  18407. /**
  18408. * @ignore Internal use only.
  18409. */
  18410. _this._includedOnlyMeshesIds = new Array();
  18411. _this.getScene().addLight(_this);
  18412. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18413. _this._buildUniformLayout();
  18414. _this.includedOnlyMeshes = new Array();
  18415. _this.excludedMeshes = new Array();
  18416. _this._resyncMeshes();
  18417. return _this;
  18418. }
  18419. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18420. /**
  18421. * If every light affecting the material is in this lightmapMode,
  18422. * material.lightmapTexture adds or multiplies
  18423. * (depends on material.useLightmapAsShadowmap)
  18424. * after every other light calculations.
  18425. */
  18426. get: function () {
  18427. return Light._LIGHTMAP_DEFAULT;
  18428. },
  18429. enumerable: true,
  18430. configurable: true
  18431. });
  18432. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18433. /**
  18434. * material.lightmapTexture as only diffuse lighting from this light
  18435. * adds only specular lighting from this light
  18436. * adds dynamic shadows
  18437. */
  18438. get: function () {
  18439. return Light._LIGHTMAP_SPECULAR;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18445. /**
  18446. * material.lightmapTexture as only lighting
  18447. * no light calculation from this light
  18448. * only adds dynamic shadows from this light
  18449. */
  18450. get: function () {
  18451. return Light._LIGHTMAP_SHADOWSONLY;
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18457. /**
  18458. * Each light type uses the default quantity according to its type:
  18459. * point/spot lights use luminous intensity
  18460. * directional lights use illuminance
  18461. */
  18462. get: function () {
  18463. return Light._INTENSITYMODE_AUTOMATIC;
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18469. /**
  18470. * lumen (lm)
  18471. */
  18472. get: function () {
  18473. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18479. /**
  18480. * candela (lm/sr)
  18481. */
  18482. get: function () {
  18483. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18489. /**
  18490. * lux (lm/m^2)
  18491. */
  18492. get: function () {
  18493. return Light._INTENSITYMODE_ILLUMINANCE;
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18499. /**
  18500. * nit (cd/m^2)
  18501. */
  18502. get: function () {
  18503. return Light._INTENSITYMODE_LUMINANCE;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18509. /**
  18510. * Light type const id of the point light.
  18511. */
  18512. get: function () {
  18513. return Light._LIGHTTYPEID_POINTLIGHT;
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18519. /**
  18520. * Light type const id of the directional light.
  18521. */
  18522. get: function () {
  18523. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18524. },
  18525. enumerable: true,
  18526. configurable: true
  18527. });
  18528. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18529. /**
  18530. * Light type const id of the spot light.
  18531. */
  18532. get: function () {
  18533. return Light._LIGHTTYPEID_SPOTLIGHT;
  18534. },
  18535. enumerable: true,
  18536. configurable: true
  18537. });
  18538. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18539. /**
  18540. * Light type const id of the hemispheric light.
  18541. */
  18542. get: function () {
  18543. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(Light.prototype, "intensityMode", {
  18549. /**
  18550. * Gets the photometric scale used to interpret the intensity.
  18551. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18552. */
  18553. get: function () {
  18554. return this._intensityMode;
  18555. },
  18556. /**
  18557. * Sets the photometric scale used to interpret the intensity.
  18558. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18559. */
  18560. set: function (value) {
  18561. this._intensityMode = value;
  18562. this._computePhotometricScale();
  18563. },
  18564. enumerable: true,
  18565. configurable: true
  18566. });
  18567. ;
  18568. ;
  18569. Object.defineProperty(Light.prototype, "radius", {
  18570. /**
  18571. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18572. */
  18573. get: function () {
  18574. return this._radius;
  18575. },
  18576. /**
  18577. * sets the light radius used by PBR Materials to simulate soft area lights.
  18578. */
  18579. set: function (value) {
  18580. this._radius = value;
  18581. this._computePhotometricScale();
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. ;
  18587. ;
  18588. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18589. /**
  18590. * Gets the only meshes impacted by this light.
  18591. */
  18592. get: function () {
  18593. return this._includedOnlyMeshes;
  18594. },
  18595. /**
  18596. * Sets the only meshes impacted by this light.
  18597. */
  18598. set: function (value) {
  18599. this._includedOnlyMeshes = value;
  18600. this._hookArrayForIncludedOnly(value);
  18601. },
  18602. enumerable: true,
  18603. configurable: true
  18604. });
  18605. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18606. /**
  18607. * Gets the meshes not impacted by this light.
  18608. */
  18609. get: function () {
  18610. return this._excludedMeshes;
  18611. },
  18612. /**
  18613. * Sets the meshes not impacted by this light.
  18614. */
  18615. set: function (value) {
  18616. this._excludedMeshes = value;
  18617. this._hookArrayForExcluded(value);
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18623. /**
  18624. * Gets the layer id use to find what meshes are not impacted by the light.
  18625. * Inactive if 0
  18626. */
  18627. get: function () {
  18628. return this._excludeWithLayerMask;
  18629. },
  18630. /**
  18631. * Sets the layer id use to find what meshes are not impacted by the light.
  18632. * Inactive if 0
  18633. */
  18634. set: function (value) {
  18635. this._excludeWithLayerMask = value;
  18636. this._resyncMeshes();
  18637. },
  18638. enumerable: true,
  18639. configurable: true
  18640. });
  18641. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18642. /**
  18643. * Gets the layer id use to find what meshes are impacted by the light.
  18644. * Inactive if 0
  18645. */
  18646. get: function () {
  18647. return this._includeOnlyWithLayerMask;
  18648. },
  18649. /**
  18650. * Sets the layer id use to find what meshes are impacted by the light.
  18651. * Inactive if 0
  18652. */
  18653. set: function (value) {
  18654. this._includeOnlyWithLayerMask = value;
  18655. this._resyncMeshes();
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(Light.prototype, "lightmapMode", {
  18661. /**
  18662. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18663. */
  18664. get: function () {
  18665. return this._lightmapMode;
  18666. },
  18667. /**
  18668. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18669. */
  18670. set: function (value) {
  18671. if (this._lightmapMode === value) {
  18672. return;
  18673. }
  18674. this._lightmapMode = value;
  18675. this._markMeshesAsLightDirty();
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. /**
  18681. * Returns the string "Light".
  18682. * @returns the class name
  18683. */
  18684. Light.prototype.getClassName = function () {
  18685. return "Light";
  18686. };
  18687. /**
  18688. * Converts the light information to a readable string for debug purpose.
  18689. * @param fullDetails Supports for multiple levels of logging within scene loading
  18690. * @returns the human readable light info
  18691. */
  18692. Light.prototype.toString = function (fullDetails) {
  18693. var ret = "Name: " + this.name;
  18694. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18695. if (this.animations) {
  18696. for (var i = 0; i < this.animations.length; i++) {
  18697. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18698. }
  18699. }
  18700. if (fullDetails) {
  18701. }
  18702. return ret;
  18703. };
  18704. /**
  18705. * Set the enabled state of this node.
  18706. * @param value - the new enabled state
  18707. * @see isEnabled
  18708. */
  18709. Light.prototype.setEnabled = function (value) {
  18710. _super.prototype.setEnabled.call(this, value);
  18711. this._resyncMeshes();
  18712. };
  18713. /**
  18714. * Returns the Light associated shadow generator if any.
  18715. * @return the associated shadow generator.
  18716. */
  18717. Light.prototype.getShadowGenerator = function () {
  18718. return this._shadowGenerator;
  18719. };
  18720. /**
  18721. * Returns a Vector3, the absolute light position in the World.
  18722. * @returns the world space position of the light
  18723. */
  18724. Light.prototype.getAbsolutePosition = function () {
  18725. return BABYLON.Vector3.Zero();
  18726. };
  18727. /**
  18728. * Specifies if the light will affect the passed mesh.
  18729. * @param mesh The mesh to test against the light
  18730. * @return true the mesh is affected otherwise, false.
  18731. */
  18732. Light.prototype.canAffectMesh = function (mesh) {
  18733. if (!mesh) {
  18734. return true;
  18735. }
  18736. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18737. return false;
  18738. }
  18739. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18740. return false;
  18741. }
  18742. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18743. return false;
  18744. }
  18745. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18746. return false;
  18747. }
  18748. return true;
  18749. };
  18750. /**
  18751. * Computes and Returns the light World matrix.
  18752. * @returns the world matrix
  18753. */
  18754. Light.prototype.getWorldMatrix = function () {
  18755. this._currentRenderId = this.getScene().getRenderId();
  18756. var worldMatrix = this._getWorldMatrix();
  18757. if (this.parent && this.parent.getWorldMatrix) {
  18758. if (!this._parentedWorldMatrix) {
  18759. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18760. }
  18761. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18762. this._markSyncedWithParent();
  18763. return this._parentedWorldMatrix;
  18764. }
  18765. return worldMatrix;
  18766. };
  18767. /**
  18768. * Sort function to order lights for rendering.
  18769. * @param a First Light object to compare to second.
  18770. * @param b Second Light object to compare first.
  18771. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18772. */
  18773. Light.CompareLightsPriority = function (a, b) {
  18774. //shadow-casting lights have priority over non-shadow-casting lights
  18775. //the renderPrioirty is a secondary sort criterion
  18776. if (a.shadowEnabled !== b.shadowEnabled) {
  18777. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18778. }
  18779. return b.renderPriority - a.renderPriority;
  18780. };
  18781. /**
  18782. * Disposes the light.
  18783. */
  18784. Light.prototype.dispose = function () {
  18785. if (this._shadowGenerator) {
  18786. this._shadowGenerator.dispose();
  18787. this._shadowGenerator = null;
  18788. }
  18789. // Animations
  18790. this.getScene().stopAnimation(this);
  18791. // Remove from meshes
  18792. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18793. var mesh = _a[_i];
  18794. mesh._removeLightSource(this);
  18795. }
  18796. this._uniformBuffer.dispose();
  18797. // Remove from scene
  18798. this.getScene().removeLight(this);
  18799. _super.prototype.dispose.call(this);
  18800. };
  18801. /**
  18802. * Returns the light type ID (integer).
  18803. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18804. */
  18805. Light.prototype.getTypeID = function () {
  18806. return 0;
  18807. };
  18808. /**
  18809. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18810. * @returns the scaled intensity in intensity mode unit
  18811. */
  18812. Light.prototype.getScaledIntensity = function () {
  18813. return this._photometricScale * this.intensity;
  18814. };
  18815. /**
  18816. * Returns a new Light object, named "name", from the current one.
  18817. * @param name The name of the cloned light
  18818. * @returns the new created light
  18819. */
  18820. Light.prototype.clone = function (name) {
  18821. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18822. if (!constructor) {
  18823. return null;
  18824. }
  18825. return BABYLON.SerializationHelper.Clone(constructor, this);
  18826. };
  18827. /**
  18828. * Serializes the current light into a Serialization object.
  18829. * @returns the serialized object.
  18830. */
  18831. Light.prototype.serialize = function () {
  18832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18833. // Type
  18834. serializationObject.type = this.getTypeID();
  18835. // Parent
  18836. if (this.parent) {
  18837. serializationObject.parentId = this.parent.id;
  18838. }
  18839. // Inclusion / exclusions
  18840. if (this.excludedMeshes.length > 0) {
  18841. serializationObject.excludedMeshesIds = [];
  18842. this.excludedMeshes.forEach(function (mesh) {
  18843. serializationObject.excludedMeshesIds.push(mesh.id);
  18844. });
  18845. }
  18846. if (this.includedOnlyMeshes.length > 0) {
  18847. serializationObject.includedOnlyMeshesIds = [];
  18848. this.includedOnlyMeshes.forEach(function (mesh) {
  18849. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18850. });
  18851. }
  18852. // Animations
  18853. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18854. serializationObject.ranges = this.serializeAnimationRanges();
  18855. return serializationObject;
  18856. };
  18857. /**
  18858. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18859. * This new light is named "name" and added to the passed scene.
  18860. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18861. * @param name The friendly name of the light
  18862. * @param scene The scene the new light will belong to
  18863. * @returns the constructor function
  18864. */
  18865. Light.GetConstructorFromName = function (type, name, scene) {
  18866. switch (type) {
  18867. case 0:
  18868. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18869. case 1:
  18870. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18871. case 2:
  18872. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18873. case 3:
  18874. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18875. }
  18876. return null;
  18877. };
  18878. /**
  18879. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18880. * @param parsedLight The JSON representation of the light
  18881. * @param scene The scene to create the parsed light in
  18882. * @returns the created light after parsing
  18883. */
  18884. Light.Parse = function (parsedLight, scene) {
  18885. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18886. if (!constructor) {
  18887. return null;
  18888. }
  18889. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18890. // Inclusion / exclusions
  18891. if (parsedLight.excludedMeshesIds) {
  18892. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18893. }
  18894. if (parsedLight.includedOnlyMeshesIds) {
  18895. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18896. }
  18897. // Parent
  18898. if (parsedLight.parentId) {
  18899. light._waitingParentId = parsedLight.parentId;
  18900. }
  18901. // Animations
  18902. if (parsedLight.animations) {
  18903. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18904. var parsedAnimation = parsedLight.animations[animationIndex];
  18905. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18906. }
  18907. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18908. }
  18909. if (parsedLight.autoAnimate) {
  18910. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18911. }
  18912. return light;
  18913. };
  18914. Light.prototype._hookArrayForExcluded = function (array) {
  18915. var _this = this;
  18916. var oldPush = array.push;
  18917. array.push = function () {
  18918. var items = [];
  18919. for (var _i = 0; _i < arguments.length; _i++) {
  18920. items[_i] = arguments[_i];
  18921. }
  18922. var result = oldPush.apply(array, items);
  18923. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18924. var item = items_1[_a];
  18925. item._resyncLighSource(_this);
  18926. }
  18927. return result;
  18928. };
  18929. var oldSplice = array.splice;
  18930. array.splice = function (index, deleteCount) {
  18931. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18932. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18933. var item = deleted_1[_i];
  18934. item._resyncLighSource(_this);
  18935. }
  18936. return deleted;
  18937. };
  18938. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18939. var item = array_1[_i];
  18940. item._resyncLighSource(this);
  18941. }
  18942. };
  18943. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18944. var _this = this;
  18945. var oldPush = array.push;
  18946. array.push = function () {
  18947. var items = [];
  18948. for (var _i = 0; _i < arguments.length; _i++) {
  18949. items[_i] = arguments[_i];
  18950. }
  18951. var result = oldPush.apply(array, items);
  18952. _this._resyncMeshes();
  18953. return result;
  18954. };
  18955. var oldSplice = array.splice;
  18956. array.splice = function (index, deleteCount) {
  18957. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18958. _this._resyncMeshes();
  18959. return deleted;
  18960. };
  18961. this._resyncMeshes();
  18962. };
  18963. Light.prototype._resyncMeshes = function () {
  18964. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18965. var mesh = _a[_i];
  18966. mesh._resyncLighSource(this);
  18967. }
  18968. };
  18969. /**
  18970. * Forces the meshes to update their light related information in their rendering used effects
  18971. * @ignore Internal Use Only
  18972. */
  18973. Light.prototype._markMeshesAsLightDirty = function () {
  18974. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18975. var mesh = _a[_i];
  18976. if (mesh._lightSources.indexOf(this) !== -1) {
  18977. mesh._markSubMeshesAsLightDirty();
  18978. }
  18979. }
  18980. };
  18981. /**
  18982. * Recomputes the cached photometric scale if needed.
  18983. */
  18984. Light.prototype._computePhotometricScale = function () {
  18985. this._photometricScale = this._getPhotometricScale();
  18986. this.getScene().resetCachedMaterial();
  18987. };
  18988. /**
  18989. * Returns the Photometric Scale according to the light type and intensity mode.
  18990. */
  18991. Light.prototype._getPhotometricScale = function () {
  18992. var photometricScale = 0.0;
  18993. var lightTypeID = this.getTypeID();
  18994. //get photometric mode
  18995. var photometricMode = this.intensityMode;
  18996. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18997. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18998. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18999. }
  19000. else {
  19001. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19002. }
  19003. }
  19004. //compute photometric scale
  19005. switch (lightTypeID) {
  19006. case Light.LIGHTTYPEID_POINTLIGHT:
  19007. case Light.LIGHTTYPEID_SPOTLIGHT:
  19008. switch (photometricMode) {
  19009. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19010. photometricScale = 1.0 / (4.0 * Math.PI);
  19011. break;
  19012. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19013. photometricScale = 1.0;
  19014. break;
  19015. case Light.INTENSITYMODE_LUMINANCE:
  19016. photometricScale = this.radius * this.radius;
  19017. break;
  19018. }
  19019. break;
  19020. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19021. switch (photometricMode) {
  19022. case Light.INTENSITYMODE_ILLUMINANCE:
  19023. photometricScale = 1.0;
  19024. break;
  19025. case Light.INTENSITYMODE_LUMINANCE:
  19026. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19027. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19028. var apexAngleRadians = this.radius;
  19029. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19030. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19031. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19032. photometricScale = solidAngle;
  19033. break;
  19034. }
  19035. break;
  19036. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19037. // No fall off in hemisperic light.
  19038. photometricScale = 1.0;
  19039. break;
  19040. }
  19041. return photometricScale;
  19042. };
  19043. /**
  19044. * Reorder the light in the scene according to their defined priority.
  19045. * @ignore Internal Use Only
  19046. */
  19047. Light.prototype._reorderLightsInScene = function () {
  19048. var scene = this.getScene();
  19049. if (this._renderPriority != 0) {
  19050. scene.requireLightSorting = true;
  19051. }
  19052. this.getScene().sortLightsByPriority();
  19053. };
  19054. //lightmapMode Consts
  19055. Light._LIGHTMAP_DEFAULT = 0;
  19056. Light._LIGHTMAP_SPECULAR = 1;
  19057. Light._LIGHTMAP_SHADOWSONLY = 2;
  19058. // Intensity Mode Consts
  19059. Light._INTENSITYMODE_AUTOMATIC = 0;
  19060. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19061. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19062. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19063. Light._INTENSITYMODE_LUMINANCE = 4;
  19064. // Light types ids const.
  19065. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19066. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19067. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19068. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19069. __decorate([
  19070. BABYLON.serializeAsColor3()
  19071. ], Light.prototype, "diffuse", void 0);
  19072. __decorate([
  19073. BABYLON.serializeAsColor3()
  19074. ], Light.prototype, "specular", void 0);
  19075. __decorate([
  19076. BABYLON.serialize()
  19077. ], Light.prototype, "intensity", void 0);
  19078. __decorate([
  19079. BABYLON.serialize()
  19080. ], Light.prototype, "range", void 0);
  19081. __decorate([
  19082. BABYLON.serialize()
  19083. ], Light.prototype, "intensityMode", null);
  19084. __decorate([
  19085. BABYLON.serialize()
  19086. ], Light.prototype, "radius", null);
  19087. __decorate([
  19088. BABYLON.serialize()
  19089. ], Light.prototype, "_renderPriority", void 0);
  19090. __decorate([
  19091. BABYLON.expandToProperty("_reorderLightsInScene")
  19092. ], Light.prototype, "renderPriority", void 0);
  19093. __decorate([
  19094. BABYLON.serialize()
  19095. ], Light.prototype, "shadowEnabled", void 0);
  19096. __decorate([
  19097. BABYLON.serialize("excludeWithLayerMask")
  19098. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19099. __decorate([
  19100. BABYLON.serialize("includeOnlyWithLayerMask")
  19101. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19102. __decorate([
  19103. BABYLON.serialize("lightmapMode")
  19104. ], Light.prototype, "_lightmapMode", void 0);
  19105. return Light;
  19106. }(BABYLON.Node));
  19107. BABYLON.Light = Light;
  19108. })(BABYLON || (BABYLON = {}));
  19109. //# sourceMappingURL=babylon.light.js.map
  19110. var BABYLON;
  19111. (function (BABYLON) {
  19112. var Camera = /** @class */ (function (_super) {
  19113. __extends(Camera, _super);
  19114. function Camera(name, position, scene) {
  19115. var _this = _super.call(this, name, scene) || this;
  19116. /**
  19117. * The vector the camera should consider as up.
  19118. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19119. */
  19120. _this.upVector = BABYLON.Vector3.Up();
  19121. _this.orthoLeft = null;
  19122. _this.orthoRight = null;
  19123. _this.orthoBottom = null;
  19124. _this.orthoTop = null;
  19125. /**
  19126. * FOV is set in Radians. (default is 0.8)
  19127. */
  19128. _this.fov = 0.8;
  19129. _this.minZ = 1;
  19130. _this.maxZ = 10000.0;
  19131. _this.inertia = 0.9;
  19132. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19133. _this.isIntermediate = false;
  19134. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19135. /**
  19136. * Restricts the camera to viewing objects with the same layerMask.
  19137. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19138. */
  19139. _this.layerMask = 0x0FFFFFFF;
  19140. /**
  19141. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19142. */
  19143. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19144. // Camera rig members
  19145. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19146. _this._rigCameras = new Array();
  19147. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19148. _this._skipRendering = false;
  19149. _this.customRenderTargets = new Array();
  19150. // Observables
  19151. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19152. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19153. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19154. _this.onRestoreStateObservable = new BABYLON.Observable();
  19155. // Cache
  19156. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19157. _this._projectionMatrix = new BABYLON.Matrix();
  19158. _this._doNotComputeProjectionMatrix = false;
  19159. _this._postProcesses = new Array();
  19160. _this._transformMatrix = BABYLON.Matrix.Zero();
  19161. _this._activeMeshes = new BABYLON.SmartArray(256);
  19162. _this._globalPosition = BABYLON.Vector3.Zero();
  19163. _this._refreshFrustumPlanes = true;
  19164. _this.getScene().addCamera(_this);
  19165. if (!_this.getScene().activeCamera) {
  19166. _this.getScene().activeCamera = _this;
  19167. }
  19168. _this.position = position;
  19169. return _this;
  19170. }
  19171. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19172. get: function () {
  19173. return Camera._PERSPECTIVE_CAMERA;
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19179. get: function () {
  19180. return Camera._ORTHOGRAPHIC_CAMERA;
  19181. },
  19182. enumerable: true,
  19183. configurable: true
  19184. });
  19185. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19186. /**
  19187. * This is the default FOV mode for perspective cameras.
  19188. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19189. *
  19190. */
  19191. get: function () {
  19192. return Camera._FOVMODE_VERTICAL_FIXED;
  19193. },
  19194. enumerable: true,
  19195. configurable: true
  19196. });
  19197. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19198. /**
  19199. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19200. *
  19201. */
  19202. get: function () {
  19203. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19204. },
  19205. enumerable: true,
  19206. configurable: true
  19207. });
  19208. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19209. get: function () {
  19210. return Camera._RIG_MODE_NONE;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19216. get: function () {
  19217. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19218. },
  19219. enumerable: true,
  19220. configurable: true
  19221. });
  19222. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19223. get: function () {
  19224. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19230. get: function () {
  19231. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19232. },
  19233. enumerable: true,
  19234. configurable: true
  19235. });
  19236. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19237. get: function () {
  19238. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19239. },
  19240. enumerable: true,
  19241. configurable: true
  19242. });
  19243. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19244. get: function () {
  19245. return Camera._RIG_MODE_VR;
  19246. },
  19247. enumerable: true,
  19248. configurable: true
  19249. });
  19250. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19251. get: function () {
  19252. return Camera._RIG_MODE_WEBVR;
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. /**
  19258. * Store current camera state (fov, position, etc..)
  19259. */
  19260. Camera.prototype.storeState = function () {
  19261. this._stateStored = true;
  19262. this._storedFov = this.fov;
  19263. return this;
  19264. };
  19265. /**
  19266. * Restores the camera state values if it has been stored. You must call storeState() first
  19267. */
  19268. Camera.prototype._restoreStateValues = function () {
  19269. if (!this._stateStored) {
  19270. return false;
  19271. }
  19272. this.fov = this._storedFov;
  19273. return true;
  19274. };
  19275. /**
  19276. * Restored camera state. You must call storeState() first
  19277. */
  19278. Camera.prototype.restoreState = function () {
  19279. if (this._restoreStateValues()) {
  19280. this.onRestoreStateObservable.notifyObservers(this);
  19281. return true;
  19282. }
  19283. return false;
  19284. };
  19285. Camera.prototype.getClassName = function () {
  19286. return "Camera";
  19287. };
  19288. /**
  19289. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19290. */
  19291. Camera.prototype.toString = function (fullDetails) {
  19292. var ret = "Name: " + this.name;
  19293. ret += ", type: " + this.getClassName();
  19294. if (this.animations) {
  19295. for (var i = 0; i < this.animations.length; i++) {
  19296. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19297. }
  19298. }
  19299. if (fullDetails) {
  19300. }
  19301. return ret;
  19302. };
  19303. Object.defineProperty(Camera.prototype, "globalPosition", {
  19304. get: function () {
  19305. return this._globalPosition;
  19306. },
  19307. enumerable: true,
  19308. configurable: true
  19309. });
  19310. Camera.prototype.getActiveMeshes = function () {
  19311. return this._activeMeshes;
  19312. };
  19313. Camera.prototype.isActiveMesh = function (mesh) {
  19314. return (this._activeMeshes.indexOf(mesh) !== -1);
  19315. };
  19316. //Cache
  19317. Camera.prototype._initCache = function () {
  19318. _super.prototype._initCache.call(this);
  19319. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19320. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19321. this._cache.mode = undefined;
  19322. this._cache.minZ = undefined;
  19323. this._cache.maxZ = undefined;
  19324. this._cache.fov = undefined;
  19325. this._cache.fovMode = undefined;
  19326. this._cache.aspectRatio = undefined;
  19327. this._cache.orthoLeft = undefined;
  19328. this._cache.orthoRight = undefined;
  19329. this._cache.orthoBottom = undefined;
  19330. this._cache.orthoTop = undefined;
  19331. this._cache.renderWidth = undefined;
  19332. this._cache.renderHeight = undefined;
  19333. };
  19334. Camera.prototype._updateCache = function (ignoreParentClass) {
  19335. if (!ignoreParentClass) {
  19336. _super.prototype._updateCache.call(this);
  19337. }
  19338. this._cache.position.copyFrom(this.position);
  19339. this._cache.upVector.copyFrom(this.upVector);
  19340. };
  19341. // Synchronized
  19342. Camera.prototype._isSynchronized = function () {
  19343. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19344. };
  19345. Camera.prototype._isSynchronizedViewMatrix = function () {
  19346. if (!_super.prototype._isSynchronized.call(this))
  19347. return false;
  19348. return this._cache.position.equals(this.position)
  19349. && this._cache.upVector.equals(this.upVector)
  19350. && this.isSynchronizedWithParent();
  19351. };
  19352. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19353. var check = this._cache.mode === this.mode
  19354. && this._cache.minZ === this.minZ
  19355. && this._cache.maxZ === this.maxZ;
  19356. if (!check) {
  19357. return false;
  19358. }
  19359. var engine = this.getEngine();
  19360. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19361. check = this._cache.fov === this.fov
  19362. && this._cache.fovMode === this.fovMode
  19363. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19364. }
  19365. else {
  19366. check = this._cache.orthoLeft === this.orthoLeft
  19367. && this._cache.orthoRight === this.orthoRight
  19368. && this._cache.orthoBottom === this.orthoBottom
  19369. && this._cache.orthoTop === this.orthoTop
  19370. && this._cache.renderWidth === engine.getRenderWidth()
  19371. && this._cache.renderHeight === engine.getRenderHeight();
  19372. }
  19373. return check;
  19374. };
  19375. // Controls
  19376. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19377. };
  19378. Camera.prototype.detachControl = function (element) {
  19379. };
  19380. Camera.prototype.update = function () {
  19381. this._checkInputs();
  19382. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19383. this._updateRigCameras();
  19384. }
  19385. };
  19386. Camera.prototype._checkInputs = function () {
  19387. this.onAfterCheckInputsObservable.notifyObservers(this);
  19388. };
  19389. Object.defineProperty(Camera.prototype, "rigCameras", {
  19390. get: function () {
  19391. return this._rigCameras;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19397. get: function () {
  19398. return this._rigPostProcess;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19404. // invalidate framebuffer
  19405. if (this._postProcesses.length > 0) {
  19406. this._postProcesses[0].markTextureDirty();
  19407. }
  19408. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19409. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19410. var cam = this._rigCameras[i];
  19411. var rigPostProcess = cam._rigPostProcess;
  19412. // for VR rig, there does not have to be a post process
  19413. if (rigPostProcess) {
  19414. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19415. if (isPass) {
  19416. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19417. cam.isIntermediate = this._postProcesses.length === 0;
  19418. }
  19419. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19420. rigPostProcess.markTextureDirty();
  19421. }
  19422. else {
  19423. cam._postProcesses = this._postProcesses.slice(0);
  19424. }
  19425. }
  19426. };
  19427. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19428. if (insertAt === void 0) { insertAt = null; }
  19429. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19430. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19431. return 0;
  19432. }
  19433. if (insertAt == null || insertAt < 0) {
  19434. this._postProcesses.push(postProcess);
  19435. }
  19436. else {
  19437. this._postProcesses.splice(insertAt, 0, postProcess);
  19438. }
  19439. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19440. return this._postProcesses.indexOf(postProcess);
  19441. };
  19442. Camera.prototype.detachPostProcess = function (postProcess) {
  19443. var idx = this._postProcesses.indexOf(postProcess);
  19444. if (idx !== -1) {
  19445. this._postProcesses.splice(idx, 1);
  19446. }
  19447. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19448. };
  19449. Camera.prototype.getWorldMatrix = function () {
  19450. if (!this._worldMatrix) {
  19451. this._worldMatrix = BABYLON.Matrix.Identity();
  19452. }
  19453. var viewMatrix = this.getViewMatrix();
  19454. viewMatrix.invertToRef(this._worldMatrix);
  19455. return this._worldMatrix;
  19456. };
  19457. Camera.prototype._getViewMatrix = function () {
  19458. return BABYLON.Matrix.Identity();
  19459. };
  19460. Camera.prototype.getViewMatrix = function (force) {
  19461. if (!force && this._isSynchronizedViewMatrix()) {
  19462. return this._computedViewMatrix;
  19463. }
  19464. this.updateCache();
  19465. this._computedViewMatrix = this._getViewMatrix();
  19466. this._currentRenderId = this.getScene().getRenderId();
  19467. this._refreshFrustumPlanes = true;
  19468. if (!this.parent || !this.parent.getWorldMatrix) {
  19469. this._globalPosition.copyFrom(this.position);
  19470. }
  19471. else {
  19472. if (!this._worldMatrix) {
  19473. this._worldMatrix = BABYLON.Matrix.Identity();
  19474. }
  19475. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19476. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19477. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19478. this._computedViewMatrix.invert();
  19479. this._markSyncedWithParent();
  19480. }
  19481. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19482. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19483. }
  19484. this.onViewMatrixChangedObservable.notifyObservers(this);
  19485. return this._computedViewMatrix;
  19486. };
  19487. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19488. this._doNotComputeProjectionMatrix = true;
  19489. if (projection !== undefined) {
  19490. this._projectionMatrix = projection;
  19491. }
  19492. };
  19493. ;
  19494. Camera.prototype.unfreezeProjectionMatrix = function () {
  19495. this._doNotComputeProjectionMatrix = false;
  19496. };
  19497. ;
  19498. Camera.prototype.getProjectionMatrix = function (force) {
  19499. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19500. return this._projectionMatrix;
  19501. }
  19502. // Cache
  19503. this._cache.mode = this.mode;
  19504. this._cache.minZ = this.minZ;
  19505. this._cache.maxZ = this.maxZ;
  19506. // Matrix
  19507. this._refreshFrustumPlanes = true;
  19508. var engine = this.getEngine();
  19509. var scene = this.getScene();
  19510. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19511. this._cache.fov = this.fov;
  19512. this._cache.fovMode = this.fovMode;
  19513. this._cache.aspectRatio = engine.getAspectRatio(this);
  19514. if (this.minZ <= 0) {
  19515. this.minZ = 0.1;
  19516. }
  19517. if (scene.useRightHandedSystem) {
  19518. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19519. }
  19520. else {
  19521. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19522. }
  19523. }
  19524. else {
  19525. var halfWidth = engine.getRenderWidth() / 2.0;
  19526. var halfHeight = engine.getRenderHeight() / 2.0;
  19527. if (scene.useRightHandedSystem) {
  19528. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19529. }
  19530. else {
  19531. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19532. }
  19533. this._cache.orthoLeft = this.orthoLeft;
  19534. this._cache.orthoRight = this.orthoRight;
  19535. this._cache.orthoBottom = this.orthoBottom;
  19536. this._cache.orthoTop = this.orthoTop;
  19537. this._cache.renderWidth = engine.getRenderWidth();
  19538. this._cache.renderHeight = engine.getRenderHeight();
  19539. }
  19540. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19541. return this._projectionMatrix;
  19542. };
  19543. Camera.prototype.getTranformationMatrix = function () {
  19544. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19545. return this._transformMatrix;
  19546. };
  19547. Camera.prototype.updateFrustumPlanes = function () {
  19548. if (!this._refreshFrustumPlanes) {
  19549. return;
  19550. }
  19551. this.getTranformationMatrix();
  19552. if (!this._frustumPlanes) {
  19553. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19554. }
  19555. else {
  19556. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19557. }
  19558. this._refreshFrustumPlanes = false;
  19559. };
  19560. Camera.prototype.isInFrustum = function (target) {
  19561. this.updateFrustumPlanes();
  19562. return target.isInFrustum(this._frustumPlanes);
  19563. };
  19564. Camera.prototype.isCompletelyInFrustum = function (target) {
  19565. this.updateFrustumPlanes();
  19566. return target.isCompletelyInFrustum(this._frustumPlanes);
  19567. };
  19568. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19569. if (length === void 0) { length = 100; }
  19570. if (!transform) {
  19571. transform = this.getWorldMatrix();
  19572. }
  19573. if (!origin) {
  19574. origin = this.position;
  19575. }
  19576. var forward = new BABYLON.Vector3(0, 0, 1);
  19577. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19578. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19579. return new BABYLON.Ray(origin, direction, length);
  19580. };
  19581. Camera.prototype.dispose = function () {
  19582. // Observables
  19583. this.onViewMatrixChangedObservable.clear();
  19584. this.onProjectionMatrixChangedObservable.clear();
  19585. this.onAfterCheckInputsObservable.clear();
  19586. this.onRestoreStateObservable.clear();
  19587. // Inputs
  19588. if (this.inputs) {
  19589. this.inputs.clear();
  19590. }
  19591. // Animations
  19592. this.getScene().stopAnimation(this);
  19593. // Remove from scene
  19594. this.getScene().removeCamera(this);
  19595. while (this._rigCameras.length > 0) {
  19596. var camera = this._rigCameras.pop();
  19597. if (camera) {
  19598. camera.dispose();
  19599. }
  19600. }
  19601. // Postprocesses
  19602. if (this._rigPostProcess) {
  19603. this._rigPostProcess.dispose(this);
  19604. this._rigPostProcess = null;
  19605. this._postProcesses = [];
  19606. }
  19607. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19608. this._rigPostProcess = null;
  19609. this._postProcesses = [];
  19610. }
  19611. else {
  19612. var i = this._postProcesses.length;
  19613. while (--i >= 0) {
  19614. this._postProcesses[i].dispose(this);
  19615. }
  19616. }
  19617. // Render targets
  19618. var i = this.customRenderTargets.length;
  19619. while (--i >= 0) {
  19620. this.customRenderTargets[i].dispose();
  19621. }
  19622. this.customRenderTargets = [];
  19623. // Active Meshes
  19624. this._activeMeshes.dispose();
  19625. _super.prototype.dispose.call(this);
  19626. };
  19627. Object.defineProperty(Camera.prototype, "leftCamera", {
  19628. // ---- Camera rigs section ----
  19629. get: function () {
  19630. if (this._rigCameras.length < 1) {
  19631. return null;
  19632. }
  19633. return this._rigCameras[0];
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(Camera.prototype, "rightCamera", {
  19639. get: function () {
  19640. if (this._rigCameras.length < 2) {
  19641. return null;
  19642. }
  19643. return this._rigCameras[1];
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Camera.prototype.getLeftTarget = function () {
  19649. if (this._rigCameras.length < 1) {
  19650. return null;
  19651. }
  19652. return this._rigCameras[0].getTarget();
  19653. };
  19654. Camera.prototype.getRightTarget = function () {
  19655. if (this._rigCameras.length < 2) {
  19656. return null;
  19657. }
  19658. return this._rigCameras[1].getTarget();
  19659. };
  19660. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19661. if (this.cameraRigMode === mode) {
  19662. return;
  19663. }
  19664. while (this._rigCameras.length > 0) {
  19665. var camera = this._rigCameras.pop();
  19666. if (camera) {
  19667. camera.dispose();
  19668. }
  19669. }
  19670. this.cameraRigMode = mode;
  19671. this._cameraRigParams = {};
  19672. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19673. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19674. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19675. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19676. // create the rig cameras, unless none
  19677. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19678. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19679. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19680. if (leftCamera && rightCamera) {
  19681. this._rigCameras.push(leftCamera);
  19682. this._rigCameras.push(rightCamera);
  19683. }
  19684. }
  19685. switch (this.cameraRigMode) {
  19686. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19687. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19688. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19689. break;
  19690. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19691. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19692. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19693. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19694. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19695. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19696. break;
  19697. case Camera.RIG_MODE_VR:
  19698. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19699. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19700. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19701. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19702. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19703. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19704. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19705. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19706. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19707. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19708. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19709. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19710. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19711. if (metrics.compensateDistortion) {
  19712. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19713. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19714. }
  19715. break;
  19716. case Camera.RIG_MODE_WEBVR:
  19717. if (rigParams.vrDisplay) {
  19718. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19719. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19720. //Left eye
  19721. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19722. this._rigCameras[0].setCameraRigParameter("left", true);
  19723. //leaving this for future reference
  19724. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19725. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19726. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19727. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19728. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19729. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19730. this._rigCameras[0].parent = this;
  19731. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19732. //Right eye
  19733. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19734. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19735. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19736. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19737. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19738. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19739. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19740. this._rigCameras[1].parent = this;
  19741. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19742. if (Camera.UseAlternateWebVRRendering) {
  19743. this._rigCameras[1]._skipRendering = true;
  19744. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19745. }
  19746. }
  19747. break;
  19748. }
  19749. this._cascadePostProcessesToRigCams();
  19750. this.update();
  19751. };
  19752. Camera.prototype._getVRProjectionMatrix = function () {
  19753. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19754. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19755. return this._projectionMatrix;
  19756. };
  19757. Camera.prototype._updateCameraRotationMatrix = function () {
  19758. //Here for WebVR
  19759. };
  19760. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19761. //Here for WebVR
  19762. };
  19763. /**
  19764. * This function MUST be overwritten by the different WebVR cameras available.
  19765. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19766. */
  19767. Camera.prototype._getWebVRProjectionMatrix = function () {
  19768. return BABYLON.Matrix.Identity();
  19769. };
  19770. /**
  19771. * This function MUST be overwritten by the different WebVR cameras available.
  19772. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19773. */
  19774. Camera.prototype._getWebVRViewMatrix = function () {
  19775. return BABYLON.Matrix.Identity();
  19776. };
  19777. Camera.prototype.setCameraRigParameter = function (name, value) {
  19778. if (!this._cameraRigParams) {
  19779. this._cameraRigParams = {};
  19780. }
  19781. this._cameraRigParams[name] = value;
  19782. //provisionnally:
  19783. if (name === "interaxialDistance") {
  19784. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19785. }
  19786. };
  19787. /**
  19788. * needs to be overridden by children so sub has required properties to be copied
  19789. */
  19790. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19791. return null;
  19792. };
  19793. /**
  19794. * May need to be overridden by children
  19795. */
  19796. Camera.prototype._updateRigCameras = function () {
  19797. for (var i = 0; i < this._rigCameras.length; i++) {
  19798. this._rigCameras[i].minZ = this.minZ;
  19799. this._rigCameras[i].maxZ = this.maxZ;
  19800. this._rigCameras[i].fov = this.fov;
  19801. }
  19802. // only update viewport when ANAGLYPH
  19803. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19804. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19805. }
  19806. };
  19807. Camera.prototype._setupInputs = function () {
  19808. };
  19809. Camera.prototype.serialize = function () {
  19810. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19811. // Type
  19812. serializationObject.type = this.getClassName();
  19813. // Parent
  19814. if (this.parent) {
  19815. serializationObject.parentId = this.parent.id;
  19816. }
  19817. if (this.inputs) {
  19818. this.inputs.serialize(serializationObject);
  19819. }
  19820. // Animations
  19821. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19822. serializationObject.ranges = this.serializeAnimationRanges();
  19823. return serializationObject;
  19824. };
  19825. Camera.prototype.clone = function (name) {
  19826. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19827. };
  19828. Camera.prototype.getDirection = function (localAxis) {
  19829. var result = BABYLON.Vector3.Zero();
  19830. this.getDirectionToRef(localAxis, result);
  19831. return result;
  19832. };
  19833. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19834. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19835. };
  19836. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19837. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19838. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19839. switch (type) {
  19840. case "ArcRotateCamera":
  19841. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19842. case "DeviceOrientationCamera":
  19843. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19844. case "FollowCamera":
  19845. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19846. case "ArcFollowCamera":
  19847. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19848. case "GamepadCamera":
  19849. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19850. case "TouchCamera":
  19851. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19852. case "VirtualJoysticksCamera":
  19853. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19854. case "WebVRFreeCamera":
  19855. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19856. case "WebVRGamepadCamera":
  19857. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19858. case "VRDeviceOrientationFreeCamera":
  19859. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19860. case "VRDeviceOrientationGamepadCamera":
  19861. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19862. case "AnaglyphArcRotateCamera":
  19863. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19864. case "AnaglyphFreeCamera":
  19865. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19866. case "AnaglyphGamepadCamera":
  19867. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19868. case "AnaglyphUniversalCamera":
  19869. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19870. case "StereoscopicArcRotateCamera":
  19871. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19872. case "StereoscopicFreeCamera":
  19873. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19874. case "StereoscopicGamepadCamera":
  19875. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19876. case "StereoscopicUniversalCamera":
  19877. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19878. case "FreeCamera":// Forcing Universal here
  19879. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19880. default:// Universal Camera is the default value
  19881. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19882. }
  19883. };
  19884. Camera.prototype.computeWorldMatrix = function () {
  19885. return this.getWorldMatrix();
  19886. };
  19887. Camera.Parse = function (parsedCamera, scene) {
  19888. var type = parsedCamera.type;
  19889. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19890. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19891. // Parent
  19892. if (parsedCamera.parentId) {
  19893. camera._waitingParentId = parsedCamera.parentId;
  19894. }
  19895. //If camera has an input manager, let it parse inputs settings
  19896. if (camera.inputs) {
  19897. camera.inputs.parse(parsedCamera);
  19898. camera._setupInputs();
  19899. }
  19900. if (camera.setPosition) {
  19901. camera.position.copyFromFloats(0, 0, 0);
  19902. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19903. }
  19904. // Target
  19905. if (parsedCamera.target) {
  19906. if (camera.setTarget) {
  19907. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19908. }
  19909. }
  19910. // Apply 3d rig, when found
  19911. if (parsedCamera.cameraRigMode) {
  19912. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19913. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19914. }
  19915. // Animations
  19916. if (parsedCamera.animations) {
  19917. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19918. var parsedAnimation = parsedCamera.animations[animationIndex];
  19919. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19920. }
  19921. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19922. }
  19923. if (parsedCamera.autoAnimate) {
  19924. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19925. }
  19926. return camera;
  19927. };
  19928. // Statics
  19929. Camera._PERSPECTIVE_CAMERA = 0;
  19930. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19931. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19932. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19933. Camera._RIG_MODE_NONE = 0;
  19934. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19935. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19936. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19937. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19938. Camera._RIG_MODE_VR = 20;
  19939. Camera._RIG_MODE_WEBVR = 21;
  19940. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19941. Camera.UseAlternateWebVRRendering = false;
  19942. __decorate([
  19943. BABYLON.serializeAsVector3()
  19944. ], Camera.prototype, "position", void 0);
  19945. __decorate([
  19946. BABYLON.serializeAsVector3()
  19947. ], Camera.prototype, "upVector", void 0);
  19948. __decorate([
  19949. BABYLON.serialize()
  19950. ], Camera.prototype, "orthoLeft", void 0);
  19951. __decorate([
  19952. BABYLON.serialize()
  19953. ], Camera.prototype, "orthoRight", void 0);
  19954. __decorate([
  19955. BABYLON.serialize()
  19956. ], Camera.prototype, "orthoBottom", void 0);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Camera.prototype, "orthoTop", void 0);
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Camera.prototype, "fov", void 0);
  19963. __decorate([
  19964. BABYLON.serialize()
  19965. ], Camera.prototype, "minZ", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Camera.prototype, "maxZ", void 0);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Camera.prototype, "inertia", void 0);
  19972. __decorate([
  19973. BABYLON.serialize()
  19974. ], Camera.prototype, "mode", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Camera.prototype, "layerMask", void 0);
  19978. __decorate([
  19979. BABYLON.serialize()
  19980. ], Camera.prototype, "fovMode", void 0);
  19981. __decorate([
  19982. BABYLON.serialize()
  19983. ], Camera.prototype, "cameraRigMode", void 0);
  19984. __decorate([
  19985. BABYLON.serialize()
  19986. ], Camera.prototype, "interaxialDistance", void 0);
  19987. __decorate([
  19988. BABYLON.serialize()
  19989. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19990. return Camera;
  19991. }(BABYLON.Node));
  19992. BABYLON.Camera = Camera;
  19993. })(BABYLON || (BABYLON = {}));
  19994. //# sourceMappingURL=babylon.camera.js.map
  19995. var BABYLON;
  19996. (function (BABYLON) {
  19997. var RenderingManager = /** @class */ (function () {
  19998. function RenderingManager(scene) {
  19999. this._renderingGroups = new Array();
  20000. this._autoClearDepthStencil = {};
  20001. this._customOpaqueSortCompareFn = {};
  20002. this._customAlphaTestSortCompareFn = {};
  20003. this._customTransparentSortCompareFn = {};
  20004. this._renderinGroupInfo = null;
  20005. this._scene = scene;
  20006. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20007. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20008. }
  20009. }
  20010. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20011. if (depth === void 0) { depth = true; }
  20012. if (stencil === void 0) { stencil = true; }
  20013. if (this._depthStencilBufferAlreadyCleaned) {
  20014. return;
  20015. }
  20016. this._scene.getEngine().clear(null, false, depth, stencil);
  20017. this._depthStencilBufferAlreadyCleaned = true;
  20018. };
  20019. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20020. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20021. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20022. var info = null;
  20023. if (observable) {
  20024. if (!this._renderinGroupInfo) {
  20025. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20026. }
  20027. info = this._renderinGroupInfo;
  20028. info.scene = this._scene;
  20029. info.camera = this._scene.activeCamera;
  20030. }
  20031. // Dispatch sprites
  20032. if (renderSprites) {
  20033. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20034. var manager = this._scene.spriteManagers[index];
  20035. this.dispatchSprites(manager);
  20036. }
  20037. }
  20038. // Render
  20039. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20040. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20041. var renderingGroup = this._renderingGroups[index];
  20042. if (!renderingGroup && !observable)
  20043. continue;
  20044. var renderingGroupMask = 0;
  20045. // Fire PRECLEAR stage
  20046. if (observable && info) {
  20047. renderingGroupMask = Math.pow(2, index);
  20048. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20049. info.renderingGroupId = index;
  20050. observable.notifyObservers(info, renderingGroupMask);
  20051. }
  20052. // Clear depth/stencil if needed
  20053. if (RenderingManager.AUTOCLEAR) {
  20054. var autoClear = this._autoClearDepthStencil[index];
  20055. if (autoClear && autoClear.autoClear) {
  20056. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20057. }
  20058. }
  20059. if (observable && info) {
  20060. // Fire PREOPAQUE stage
  20061. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20062. observable.notifyObservers(info, renderingGroupMask);
  20063. // Fire PRETRANSPARENT stage
  20064. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20065. observable.notifyObservers(info, renderingGroupMask);
  20066. }
  20067. if (renderingGroup)
  20068. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20069. // Fire POSTTRANSPARENT stage
  20070. if (observable && info) {
  20071. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20072. observable.notifyObservers(info, renderingGroupMask);
  20073. }
  20074. }
  20075. };
  20076. RenderingManager.prototype.reset = function () {
  20077. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20078. var renderingGroup = this._renderingGroups[index];
  20079. if (renderingGroup) {
  20080. renderingGroup.prepare();
  20081. }
  20082. }
  20083. };
  20084. RenderingManager.prototype.dispose = function () {
  20085. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20086. var renderingGroup = this._renderingGroups[index];
  20087. if (renderingGroup) {
  20088. renderingGroup.dispose();
  20089. }
  20090. }
  20091. this._renderingGroups.length = 0;
  20092. };
  20093. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20094. if (this._renderingGroups[renderingGroupId] === undefined) {
  20095. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20096. }
  20097. };
  20098. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20099. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20100. this._prepareRenderingGroup(renderingGroupId);
  20101. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20102. };
  20103. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20104. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20105. this._prepareRenderingGroup(renderingGroupId);
  20106. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20107. };
  20108. /**
  20109. * @param subMesh The submesh to dispatch
  20110. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20111. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20112. */
  20113. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20114. if (mesh === undefined) {
  20115. mesh = subMesh.getMesh();
  20116. }
  20117. var renderingGroupId = mesh.renderingGroupId || 0;
  20118. this._prepareRenderingGroup(renderingGroupId);
  20119. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20120. };
  20121. /**
  20122. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20123. * This allowed control for front to back rendering or reversly depending of the special needs.
  20124. *
  20125. * @param renderingGroupId The rendering group id corresponding to its index
  20126. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20127. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20128. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20129. */
  20130. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20131. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20132. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20133. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20134. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20135. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20136. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20137. if (this._renderingGroups[renderingGroupId]) {
  20138. var group = this._renderingGroups[renderingGroupId];
  20139. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20140. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20141. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20142. }
  20143. };
  20144. /**
  20145. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20146. *
  20147. * @param renderingGroupId The rendering group id corresponding to its index
  20148. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20149. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20150. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20151. */
  20152. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20153. if (depth === void 0) { depth = true; }
  20154. if (stencil === void 0) { stencil = true; }
  20155. this._autoClearDepthStencil[renderingGroupId] = {
  20156. autoClear: autoClearDepthStencil,
  20157. depth: depth,
  20158. stencil: stencil
  20159. };
  20160. };
  20161. /**
  20162. * The max id used for rendering groups (not included)
  20163. */
  20164. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20165. /**
  20166. * The min id used for rendering groups (included)
  20167. */
  20168. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20169. /**
  20170. * Used to globally prevent autoclearing scenes.
  20171. */
  20172. RenderingManager.AUTOCLEAR = true;
  20173. return RenderingManager;
  20174. }());
  20175. BABYLON.RenderingManager = RenderingManager;
  20176. })(BABYLON || (BABYLON = {}));
  20177. //# sourceMappingURL=babylon.renderingManager.js.map
  20178. var BABYLON;
  20179. (function (BABYLON) {
  20180. var RenderingGroup = /** @class */ (function () {
  20181. /**
  20182. * Creates a new rendering group.
  20183. * @param index The rendering group index
  20184. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20185. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20186. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20187. */
  20188. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20189. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20190. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20191. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20192. this.index = index;
  20193. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20194. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20195. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20196. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20197. this._particleSystems = new BABYLON.SmartArray(256);
  20198. this._spriteManagers = new BABYLON.SmartArray(256);
  20199. this._edgesRenderers = new BABYLON.SmartArray(16);
  20200. this._scene = scene;
  20201. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20202. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20203. this.transparentSortCompareFn = transparentSortCompareFn;
  20204. }
  20205. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20206. /**
  20207. * Set the opaque sort comparison function.
  20208. * If null the sub meshes will be render in the order they were created
  20209. */
  20210. set: function (value) {
  20211. this._opaqueSortCompareFn = value;
  20212. if (value) {
  20213. this._renderOpaque = this.renderOpaqueSorted;
  20214. }
  20215. else {
  20216. this._renderOpaque = RenderingGroup.renderUnsorted;
  20217. }
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20223. /**
  20224. * Set the alpha test sort comparison function.
  20225. * If null the sub meshes will be render in the order they were created
  20226. */
  20227. set: function (value) {
  20228. this._alphaTestSortCompareFn = value;
  20229. if (value) {
  20230. this._renderAlphaTest = this.renderAlphaTestSorted;
  20231. }
  20232. else {
  20233. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20234. }
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20240. /**
  20241. * Set the transparent sort comparison function.
  20242. * If null the sub meshes will be render in the order they were created
  20243. */
  20244. set: function (value) {
  20245. if (value) {
  20246. this._transparentSortCompareFn = value;
  20247. }
  20248. else {
  20249. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20250. }
  20251. this._renderTransparent = this.renderTransparentSorted;
  20252. },
  20253. enumerable: true,
  20254. configurable: true
  20255. });
  20256. /**
  20257. * Render all the sub meshes contained in the group.
  20258. * @param customRenderFunction Used to override the default render behaviour of the group.
  20259. * @returns true if rendered some submeshes.
  20260. */
  20261. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20262. if (customRenderFunction) {
  20263. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20264. return;
  20265. }
  20266. var engine = this._scene.getEngine();
  20267. // Depth only
  20268. if (this._depthOnlySubMeshes.length !== 0) {
  20269. engine.setColorWrite(false);
  20270. this._renderAlphaTest(this._depthOnlySubMeshes);
  20271. engine.setColorWrite(true);
  20272. }
  20273. // Opaque
  20274. if (this._opaqueSubMeshes.length !== 0) {
  20275. this._renderOpaque(this._opaqueSubMeshes);
  20276. }
  20277. // Alpha test
  20278. if (this._alphaTestSubMeshes.length !== 0) {
  20279. this._renderAlphaTest(this._alphaTestSubMeshes);
  20280. }
  20281. var stencilState = engine.getStencilBuffer();
  20282. engine.setStencilBuffer(false);
  20283. // Sprites
  20284. if (renderSprites) {
  20285. this._renderSprites();
  20286. }
  20287. // Particles
  20288. if (renderParticles) {
  20289. this._renderParticles(activeMeshes);
  20290. }
  20291. if (this.onBeforeTransparentRendering) {
  20292. this.onBeforeTransparentRendering();
  20293. }
  20294. // Transparent
  20295. if (this._transparentSubMeshes.length !== 0) {
  20296. this._renderTransparent(this._transparentSubMeshes);
  20297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20298. }
  20299. // Set back stencil to false in case it changes before the edge renderer.
  20300. engine.setStencilBuffer(false);
  20301. // Edges
  20302. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20303. this._edgesRenderers.data[edgesRendererIndex].render();
  20304. }
  20305. // Restore Stencil state.
  20306. engine.setStencilBuffer(stencilState);
  20307. };
  20308. /**
  20309. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20310. * @param subMeshes The submeshes to render
  20311. */
  20312. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20313. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20314. };
  20315. /**
  20316. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20317. * @param subMeshes The submeshes to render
  20318. */
  20319. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20320. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20321. };
  20322. /**
  20323. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20324. * @param subMeshes The submeshes to render
  20325. */
  20326. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20327. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20328. };
  20329. /**
  20330. * Renders the submeshes in a specified order.
  20331. * @param subMeshes The submeshes to sort before render
  20332. * @param sortCompareFn The comparison function use to sort
  20333. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20334. * @param transparent Specifies to activate blending if true
  20335. */
  20336. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20337. var subIndex = 0;
  20338. var subMesh;
  20339. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20340. for (; subIndex < subMeshes.length; subIndex++) {
  20341. subMesh = subMeshes.data[subIndex];
  20342. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20343. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20344. }
  20345. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20346. if (sortCompareFn) {
  20347. sortedArray.sort(sortCompareFn);
  20348. }
  20349. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20350. subMesh = sortedArray[subIndex];
  20351. if (transparent) {
  20352. var material = subMesh.getMaterial();
  20353. if (material && material.needDepthPrePass) {
  20354. var engine = material.getScene().getEngine();
  20355. engine.setColorWrite(false);
  20356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20357. subMesh.render(false);
  20358. engine.setColorWrite(true);
  20359. }
  20360. }
  20361. subMesh.render(transparent);
  20362. }
  20363. };
  20364. /**
  20365. * Renders the submeshes in the order they were dispatched (no sort applied).
  20366. * @param subMeshes The submeshes to render
  20367. */
  20368. RenderingGroup.renderUnsorted = function (subMeshes) {
  20369. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20370. var submesh = subMeshes.data[subIndex];
  20371. submesh.render(false);
  20372. }
  20373. };
  20374. /**
  20375. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20376. * are rendered back to front if in the same alpha index.
  20377. *
  20378. * @param a The first submesh
  20379. * @param b The second submesh
  20380. * @returns The result of the comparison
  20381. */
  20382. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20383. // Alpha index first
  20384. if (a._alphaIndex > b._alphaIndex) {
  20385. return 1;
  20386. }
  20387. if (a._alphaIndex < b._alphaIndex) {
  20388. return -1;
  20389. }
  20390. // Then distance to camera
  20391. return RenderingGroup.backToFrontSortCompare(a, b);
  20392. };
  20393. /**
  20394. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20395. * are rendered back to front.
  20396. *
  20397. * @param a The first submesh
  20398. * @param b The second submesh
  20399. * @returns The result of the comparison
  20400. */
  20401. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20402. // Then distance to camera
  20403. if (a._distanceToCamera < b._distanceToCamera) {
  20404. return 1;
  20405. }
  20406. if (a._distanceToCamera > b._distanceToCamera) {
  20407. return -1;
  20408. }
  20409. return 0;
  20410. };
  20411. /**
  20412. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20413. * are rendered front to back (prevent overdraw).
  20414. *
  20415. * @param a The first submesh
  20416. * @param b The second submesh
  20417. * @returns The result of the comparison
  20418. */
  20419. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20420. // Then distance to camera
  20421. if (a._distanceToCamera < b._distanceToCamera) {
  20422. return -1;
  20423. }
  20424. if (a._distanceToCamera > b._distanceToCamera) {
  20425. return 1;
  20426. }
  20427. return 0;
  20428. };
  20429. /**
  20430. * Resets the different lists of submeshes to prepare a new frame.
  20431. */
  20432. RenderingGroup.prototype.prepare = function () {
  20433. this._opaqueSubMeshes.reset();
  20434. this._transparentSubMeshes.reset();
  20435. this._alphaTestSubMeshes.reset();
  20436. this._depthOnlySubMeshes.reset();
  20437. this._particleSystems.reset();
  20438. this._spriteManagers.reset();
  20439. this._edgesRenderers.reset();
  20440. };
  20441. RenderingGroup.prototype.dispose = function () {
  20442. this._opaqueSubMeshes.dispose();
  20443. this._transparentSubMeshes.dispose();
  20444. this._alphaTestSubMeshes.dispose();
  20445. this._depthOnlySubMeshes.dispose();
  20446. this._particleSystems.dispose();
  20447. this._spriteManagers.dispose();
  20448. this._edgesRenderers.dispose();
  20449. };
  20450. /**
  20451. * Inserts the submesh in its correct queue depending on its material.
  20452. * @param subMesh The submesh to dispatch
  20453. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20454. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20455. */
  20456. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20457. // Get mesh and materials if not provided
  20458. if (mesh === undefined) {
  20459. mesh = subMesh.getMesh();
  20460. }
  20461. if (material === undefined) {
  20462. material = subMesh.getMaterial();
  20463. }
  20464. if (material === null || material === undefined) {
  20465. return;
  20466. }
  20467. if (material.needAlphaBlendingForMesh(mesh)) {
  20468. this._transparentSubMeshes.push(subMesh);
  20469. }
  20470. else if (material.needAlphaTesting()) {
  20471. if (material.needDepthPrePass) {
  20472. this._depthOnlySubMeshes.push(subMesh);
  20473. }
  20474. this._alphaTestSubMeshes.push(subMesh);
  20475. }
  20476. else {
  20477. if (material.needDepthPrePass) {
  20478. this._depthOnlySubMeshes.push(subMesh);
  20479. }
  20480. this._opaqueSubMeshes.push(subMesh); // Opaque
  20481. }
  20482. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20483. this._edgesRenderers.push(mesh._edgesRenderer);
  20484. }
  20485. };
  20486. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20487. this._spriteManagers.push(spriteManager);
  20488. };
  20489. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20490. this._particleSystems.push(particleSystem);
  20491. };
  20492. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20493. if (this._particleSystems.length === 0) {
  20494. return;
  20495. }
  20496. // Particles
  20497. var activeCamera = this._scene.activeCamera;
  20498. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20499. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20500. var particleSystem = this._particleSystems.data[particleIndex];
  20501. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20502. continue;
  20503. }
  20504. var emitter = particleSystem.emitter;
  20505. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20506. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20507. }
  20508. }
  20509. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20510. };
  20511. RenderingGroup.prototype._renderSprites = function () {
  20512. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20513. return;
  20514. }
  20515. // Sprites
  20516. var activeCamera = this._scene.activeCamera;
  20517. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20518. for (var id = 0; id < this._spriteManagers.length; id++) {
  20519. var spriteManager = this._spriteManagers.data[id];
  20520. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20521. spriteManager.render();
  20522. }
  20523. }
  20524. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20525. };
  20526. return RenderingGroup;
  20527. }());
  20528. BABYLON.RenderingGroup = RenderingGroup;
  20529. })(BABYLON || (BABYLON = {}));
  20530. //# sourceMappingURL=babylon.renderingGroup.js.map
  20531. var BABYLON;
  20532. (function (BABYLON) {
  20533. var ClickInfo = /** @class */ (function () {
  20534. function ClickInfo() {
  20535. this._singleClick = false;
  20536. this._doubleClick = false;
  20537. this._hasSwiped = false;
  20538. this._ignore = false;
  20539. }
  20540. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20541. get: function () {
  20542. return this._singleClick;
  20543. },
  20544. set: function (b) {
  20545. this._singleClick = b;
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20551. get: function () {
  20552. return this._doubleClick;
  20553. },
  20554. set: function (b) {
  20555. this._doubleClick = b;
  20556. },
  20557. enumerable: true,
  20558. configurable: true
  20559. });
  20560. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20561. get: function () {
  20562. return this._hasSwiped;
  20563. },
  20564. set: function (b) {
  20565. this._hasSwiped = b;
  20566. },
  20567. enumerable: true,
  20568. configurable: true
  20569. });
  20570. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20571. get: function () {
  20572. return this._ignore;
  20573. },
  20574. set: function (b) {
  20575. this._ignore = b;
  20576. },
  20577. enumerable: true,
  20578. configurable: true
  20579. });
  20580. return ClickInfo;
  20581. }());
  20582. /**
  20583. * This class is used by the onRenderingGroupObservable
  20584. */
  20585. var RenderingGroupInfo = /** @class */ (function () {
  20586. function RenderingGroupInfo() {
  20587. }
  20588. /**
  20589. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20590. * This stage will be fired no matter what
  20591. */
  20592. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20593. /**
  20594. * Called before opaque object are rendered.
  20595. * This stage will be fired only if there's 3D Opaque content to render
  20596. */
  20597. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20598. /**
  20599. * Called after the opaque objects are rendered and before the transparent ones
  20600. * This stage will be fired only if there's 3D transparent content to render
  20601. */
  20602. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20603. /**
  20604. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20605. * This stage will be fired no matter what
  20606. */
  20607. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20608. return RenderingGroupInfo;
  20609. }());
  20610. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20611. /**
  20612. * Represents a scene to be rendered by the engine.
  20613. * @see http://doc.babylonjs.com/page.php?p=21911
  20614. */
  20615. var Scene = /** @class */ (function () {
  20616. /**
  20617. * @constructor
  20618. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20619. */
  20620. function Scene(engine) {
  20621. // Members
  20622. this.autoClear = true;
  20623. this.autoClearDepthAndStencil = true;
  20624. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20625. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20626. this.forceWireframe = false;
  20627. this._forcePointsCloud = false;
  20628. this.forceShowBoundingBoxes = false;
  20629. this.animationsEnabled = true;
  20630. this.useConstantAnimationDeltaTime = false;
  20631. this.constantlyUpdateMeshUnderPointer = false;
  20632. this.hoverCursor = "pointer";
  20633. this.defaultCursor = "";
  20634. /**
  20635. * This is used to call preventDefault() on pointer down
  20636. * in order to block unwanted artifacts like system double clicks
  20637. */
  20638. this.preventDefaultOnPointerDown = true;
  20639. // Metadata
  20640. this.metadata = null;
  20641. /**
  20642. * An event triggered when the scene is disposed.
  20643. * @type {BABYLON.Observable}
  20644. */
  20645. this.onDisposeObservable = new BABYLON.Observable();
  20646. /**
  20647. * An event triggered before rendering the scene (right after animations and physics)
  20648. * @type {BABYLON.Observable}
  20649. */
  20650. this.onBeforeRenderObservable = new BABYLON.Observable();
  20651. /**
  20652. * An event triggered after rendering the scene
  20653. * @type {BABYLON.Observable}
  20654. */
  20655. this.onAfterRenderObservable = new BABYLON.Observable();
  20656. /**
  20657. * An event triggered before animating the scene
  20658. * @type {BABYLON.Observable}
  20659. */
  20660. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20661. /**
  20662. * An event triggered after animations processing
  20663. * @type {BABYLON.Observable}
  20664. */
  20665. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20666. /**
  20667. * An event triggered before draw calls are ready to be sent
  20668. * @type {BABYLON.Observable}
  20669. */
  20670. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20671. /**
  20672. * An event triggered after draw calls have been sent
  20673. * @type {BABYLON.Observable}
  20674. */
  20675. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20676. /**
  20677. * An event triggered when physic simulation is about to be run
  20678. * @type {BABYLON.Observable}
  20679. */
  20680. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20681. /**
  20682. * An event triggered when physic simulation has been done
  20683. * @type {BABYLON.Observable}
  20684. */
  20685. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20686. /**
  20687. * An event triggered when the scene is ready
  20688. * @type {BABYLON.Observable}
  20689. */
  20690. this.onReadyObservable = new BABYLON.Observable();
  20691. /**
  20692. * An event triggered before rendering a camera
  20693. * @type {BABYLON.Observable}
  20694. */
  20695. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20696. /**
  20697. * An event triggered after rendering a camera
  20698. * @type {BABYLON.Observable}
  20699. */
  20700. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20701. /**
  20702. * An event triggered when active meshes evaluation is about to start
  20703. * @type {BABYLON.Observable}
  20704. */
  20705. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20706. /**
  20707. * An event triggered when active meshes evaluation is done
  20708. * @type {BABYLON.Observable}
  20709. */
  20710. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20711. /**
  20712. * An event triggered when particles rendering is about to start
  20713. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20714. * @type {BABYLON.Observable}
  20715. */
  20716. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20717. /**
  20718. * An event triggered when particles rendering is done
  20719. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20720. * @type {BABYLON.Observable}
  20721. */
  20722. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20723. /**
  20724. * An event triggered when sprites rendering is about to start
  20725. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20726. * @type {BABYLON.Observable}
  20727. */
  20728. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20729. /**
  20730. * An event triggered when sprites rendering is done
  20731. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20732. * @type {BABYLON.Observable}
  20733. */
  20734. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20735. /**
  20736. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20737. * @type {BABYLON.Observable}
  20738. */
  20739. this.onDataLoadedObservable = new BABYLON.Observable();
  20740. /**
  20741. * An event triggered when a camera is created
  20742. * @type {BABYLON.Observable}
  20743. */
  20744. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20745. /**
  20746. * An event triggered when a camera is removed
  20747. * @type {BABYLON.Observable}
  20748. */
  20749. this.onCameraRemovedObservable = new BABYLON.Observable();
  20750. /**
  20751. * An event triggered when a light is created
  20752. * @type {BABYLON.Observable}
  20753. */
  20754. this.onNewLightAddedObservable = new BABYLON.Observable();
  20755. /**
  20756. * An event triggered when a light is removed
  20757. * @type {BABYLON.Observable}
  20758. */
  20759. this.onLightRemovedObservable = new BABYLON.Observable();
  20760. /**
  20761. * An event triggered when a geometry is created
  20762. * @type {BABYLON.Observable}
  20763. */
  20764. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20765. /**
  20766. * An event triggered when a geometry is removed
  20767. * @type {BABYLON.Observable}
  20768. */
  20769. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20770. /**
  20771. * An event triggered when a transform node is created
  20772. * @type {BABYLON.Observable}
  20773. */
  20774. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20775. /**
  20776. * An event triggered when a transform node is removed
  20777. * @type {BABYLON.Observable}
  20778. */
  20779. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20780. /**
  20781. * An event triggered when a mesh is created
  20782. * @type {BABYLON.Observable}
  20783. */
  20784. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20785. /**
  20786. * An event triggered when a mesh is removed
  20787. * @type {BABYLON.Observable}
  20788. */
  20789. this.onMeshRemovedObservable = new BABYLON.Observable();
  20790. /**
  20791. * An event triggered when render targets are about to be rendered
  20792. * Can happen multiple times per frame.
  20793. * @type {BABYLON.Observable}
  20794. */
  20795. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20796. /**
  20797. * An event triggered when render targets were rendered.
  20798. * Can happen multiple times per frame.
  20799. * @type {BABYLON.Observable}
  20800. */
  20801. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20802. /**
  20803. * An event triggered before calculating deterministic simulation step
  20804. * @type {BABYLON.Observable}
  20805. */
  20806. this.onBeforeStepObservable = new BABYLON.Observable();
  20807. /**
  20808. * An event triggered after calculating deterministic simulation step
  20809. * @type {BABYLON.Observable}
  20810. */
  20811. this.onAfterStepObservable = new BABYLON.Observable();
  20812. /**
  20813. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20814. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20815. * 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)
  20816. */
  20817. this.onRenderingGroupObservable = new BABYLON.Observable();
  20818. // Animations
  20819. this.animations = [];
  20820. /**
  20821. * 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).
  20822. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20823. */
  20824. this.onPrePointerObservable = new BABYLON.Observable();
  20825. /**
  20826. * Observable event triggered each time an input event is received from the rendering canvas
  20827. */
  20828. this.onPointerObservable = new BABYLON.Observable();
  20829. this._meshPickProceed = false;
  20830. this._currentPickResult = null;
  20831. this._previousPickResult = null;
  20832. this._totalPointersPressed = 0;
  20833. this._doubleClickOccured = false;
  20834. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20835. this.cameraToUseForPointers = null;
  20836. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20837. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20838. this._startingPointerTime = 0;
  20839. this._previousStartingPointerTime = 0;
  20840. // Deterministic lockstep
  20841. this._timeAccumulator = 0;
  20842. this._currentStepId = 0;
  20843. this._currentInternalStep = 0;
  20844. // Keyboard
  20845. /**
  20846. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20847. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20848. */
  20849. this.onPreKeyboardObservable = new BABYLON.Observable();
  20850. /**
  20851. * Observable event triggered each time an keyboard event is received from the hosting window
  20852. */
  20853. this.onKeyboardObservable = new BABYLON.Observable();
  20854. // Coordinate system
  20855. /**
  20856. * use right-handed coordinate system on this scene.
  20857. * @type {boolean}
  20858. */
  20859. this._useRightHandedSystem = false;
  20860. // Fog
  20861. this._fogEnabled = true;
  20862. this._fogMode = Scene.FOGMODE_NONE;
  20863. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20864. this.fogDensity = 0.1;
  20865. this.fogStart = 0;
  20866. this.fogEnd = 1000.0;
  20867. // Lights
  20868. /**
  20869. * is shadow enabled on this scene.
  20870. * @type {boolean}
  20871. */
  20872. this._shadowsEnabled = true;
  20873. /**
  20874. * is light enabled on this scene.
  20875. * @type {boolean}
  20876. */
  20877. this._lightsEnabled = true;
  20878. /**
  20879. * All of the lights added to this scene.
  20880. * @see BABYLON.Light
  20881. * @type {BABYLON.Light[]}
  20882. */
  20883. this.lights = new Array();
  20884. // Cameras
  20885. /** All of the cameras added to this scene. */
  20886. this.cameras = new Array();
  20887. /** All of the active cameras added to this scene. */
  20888. this.activeCameras = new Array();
  20889. // Meshes
  20890. /**
  20891. * All of the tranform nodes added to this scene.
  20892. * @see BABYLON.TransformNode
  20893. * @type {BABYLON.TransformNode[]}
  20894. */
  20895. this.transformNodes = new Array();
  20896. /**
  20897. * All of the (abstract) meshes added to this scene.
  20898. * @see BABYLON.AbstractMesh
  20899. * @type {BABYLON.AbstractMesh[]}
  20900. */
  20901. this.meshes = new Array();
  20902. /**
  20903. * All of the animation groups added to this scene.
  20904. * @see BABYLON.AnimationGroup
  20905. * @type {BABYLON.AnimationGroup[]}
  20906. */
  20907. this.animationGroups = new Array();
  20908. // Geometries
  20909. this._geometries = new Array();
  20910. this.materials = new Array();
  20911. this.multiMaterials = new Array();
  20912. // Textures
  20913. this._texturesEnabled = true;
  20914. this.textures = new Array();
  20915. // Particles
  20916. this.particlesEnabled = true;
  20917. this.particleSystems = new Array();
  20918. // Sprites
  20919. this.spritesEnabled = true;
  20920. this.spriteManagers = new Array();
  20921. /**
  20922. * The list of layers (background and foreground) of the scene.
  20923. */
  20924. this.layers = new Array();
  20925. /**
  20926. * The list of effect layers (highlights/glow) contained in the scene.
  20927. */
  20928. this.effectLayers = new Array();
  20929. // Skeletons
  20930. this._skeletonsEnabled = true;
  20931. this.skeletons = new Array();
  20932. // Morph targets
  20933. this.morphTargetManagers = new Array();
  20934. // Lens flares
  20935. this.lensFlaresEnabled = true;
  20936. this.lensFlareSystems = new Array();
  20937. // Collisions
  20938. this.collisionsEnabled = true;
  20939. /** Defines the gravity applied to this scene */
  20940. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20941. // Postprocesses
  20942. this.postProcesses = new Array();
  20943. this.postProcessesEnabled = true;
  20944. // Customs render targets
  20945. this.renderTargetsEnabled = true;
  20946. this.dumpNextRenderTargets = false;
  20947. this.customRenderTargets = new Array();
  20948. // Imported meshes
  20949. this.importedMeshesFiles = new Array();
  20950. // Probes
  20951. this.probesEnabled = true;
  20952. this.reflectionProbes = new Array();
  20953. this._actionManagers = new Array();
  20954. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20955. // Procedural textures
  20956. this.proceduralTexturesEnabled = true;
  20957. this._proceduralTextures = new Array();
  20958. this.soundTracks = new Array();
  20959. this._audioEnabled = true;
  20960. this._headphone = false;
  20961. // Performance counters
  20962. this._totalVertices = new BABYLON.PerfCounter();
  20963. this._activeIndices = new BABYLON.PerfCounter();
  20964. this._activeParticles = new BABYLON.PerfCounter();
  20965. this._activeBones = new BABYLON.PerfCounter();
  20966. this._animationTime = 0;
  20967. this.animationTimeScale = 1;
  20968. this._renderId = 0;
  20969. this._executeWhenReadyTimeoutId = -1;
  20970. this._intermediateRendering = false;
  20971. this._viewUpdateFlag = -1;
  20972. this._projectionUpdateFlag = -1;
  20973. this._alternateViewUpdateFlag = -1;
  20974. this._alternateProjectionUpdateFlag = -1;
  20975. this._toBeDisposed = new BABYLON.SmartArray(256);
  20976. this._activeRequests = new Array();
  20977. this._pendingData = new Array();
  20978. this._isDisposed = false;
  20979. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20980. this._activeMeshes = new BABYLON.SmartArray(256);
  20981. this._processedMaterials = new BABYLON.SmartArray(256);
  20982. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20983. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20984. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20985. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20986. this._activeAnimatables = new Array();
  20987. this._transformMatrix = BABYLON.Matrix.Zero();
  20988. this._useAlternateCameraConfiguration = false;
  20989. this._alternateRendering = false;
  20990. this.requireLightSorting = false;
  20991. this._activeMeshesFrozen = false;
  20992. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20993. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20994. this._engine.scenes.push(this);
  20995. this._uid = null;
  20996. this._renderingManager = new BABYLON.RenderingManager(this);
  20997. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20998. if (BABYLON.OutlineRenderer) {
  20999. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21000. }
  21001. if (BABYLON.Tools.IsWindowObjectExist()) {
  21002. this.attachControl();
  21003. }
  21004. //simplification queue
  21005. if (BABYLON.SimplificationQueue) {
  21006. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21007. }
  21008. //collision coordinator initialization. For now legacy per default.
  21009. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21010. // Uniform Buffer
  21011. this._createUbo();
  21012. // Default Image processing definition.
  21013. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21014. }
  21015. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21016. /** The fog is deactivated */
  21017. get: function () {
  21018. return Scene._FOGMODE_NONE;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21024. /** The fog density is following an exponential function */
  21025. get: function () {
  21026. return Scene._FOGMODE_EXP;
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21032. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21033. get: function () {
  21034. return Scene._FOGMODE_EXP2;
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21040. /** The fog density is following a linear function. */
  21041. get: function () {
  21042. return Scene._FOGMODE_LINEAR;
  21043. },
  21044. enumerable: true,
  21045. configurable: true
  21046. });
  21047. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21048. /**
  21049. * Texture used in all pbr material as the reflection texture.
  21050. * As in the majority of the scene they are the same (exception for multi room and so on),
  21051. * this is easier to reference from here than from all the materials.
  21052. */
  21053. get: function () {
  21054. return this._environmentTexture;
  21055. },
  21056. /**
  21057. * Texture used in all pbr material as the reflection texture.
  21058. * As in the majority of the scene they are the same (exception for multi room and so on),
  21059. * this is easier to set here than in all the materials.
  21060. */
  21061. set: function (value) {
  21062. if (this._environmentTexture === value) {
  21063. return;
  21064. }
  21065. this._environmentTexture = value;
  21066. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21072. /**
  21073. * Default image processing configuration used either in the rendering
  21074. * Forward main pass or through the imageProcessingPostProcess if present.
  21075. * As in the majority of the scene they are the same (exception for multi camera),
  21076. * this is easier to reference from here than from all the materials and post process.
  21077. *
  21078. * No setter as we it is a shared configuration, you can set the values instead.
  21079. */
  21080. get: function () {
  21081. return this._imageProcessingConfiguration;
  21082. },
  21083. enumerable: true,
  21084. configurable: true
  21085. });
  21086. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21087. get: function () {
  21088. return this._forcePointsCloud;
  21089. },
  21090. set: function (value) {
  21091. if (this._forcePointsCloud === value) {
  21092. return;
  21093. }
  21094. this._forcePointsCloud = value;
  21095. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21096. },
  21097. enumerable: true,
  21098. configurable: true
  21099. });
  21100. Object.defineProperty(Scene.prototype, "onDispose", {
  21101. /** A function to be executed when this scene is disposed. */
  21102. set: function (callback) {
  21103. if (this._onDisposeObserver) {
  21104. this.onDisposeObservable.remove(this._onDisposeObserver);
  21105. }
  21106. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21107. },
  21108. enumerable: true,
  21109. configurable: true
  21110. });
  21111. Object.defineProperty(Scene.prototype, "beforeRender", {
  21112. /** A function to be executed before rendering this scene */
  21113. set: function (callback) {
  21114. if (this._onBeforeRenderObserver) {
  21115. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21116. }
  21117. if (callback) {
  21118. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21119. }
  21120. },
  21121. enumerable: true,
  21122. configurable: true
  21123. });
  21124. Object.defineProperty(Scene.prototype, "afterRender", {
  21125. /** A function to be executed after rendering this scene */
  21126. set: function (callback) {
  21127. if (this._onAfterRenderObserver) {
  21128. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21129. }
  21130. if (callback) {
  21131. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21132. }
  21133. },
  21134. enumerable: true,
  21135. configurable: true
  21136. });
  21137. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21138. set: function (callback) {
  21139. if (this._onBeforeCameraRenderObserver) {
  21140. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21141. }
  21142. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21148. set: function (callback) {
  21149. if (this._onAfterCameraRenderObserver) {
  21150. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21151. }
  21152. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21158. get: function () {
  21159. if (!this._gamepadManager) {
  21160. this._gamepadManager = new BABYLON.GamepadManager(this);
  21161. }
  21162. return this._gamepadManager;
  21163. },
  21164. enumerable: true,
  21165. configurable: true
  21166. });
  21167. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21168. get: function () {
  21169. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21170. },
  21171. enumerable: true,
  21172. configurable: true
  21173. });
  21174. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21175. get: function () {
  21176. return this._useRightHandedSystem;
  21177. },
  21178. set: function (value) {
  21179. if (this._useRightHandedSystem === value) {
  21180. return;
  21181. }
  21182. this._useRightHandedSystem = value;
  21183. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21184. },
  21185. enumerable: true,
  21186. configurable: true
  21187. });
  21188. Scene.prototype.setStepId = function (newStepId) {
  21189. this._currentStepId = newStepId;
  21190. };
  21191. ;
  21192. Scene.prototype.getStepId = function () {
  21193. return this._currentStepId;
  21194. };
  21195. ;
  21196. Scene.prototype.getInternalStep = function () {
  21197. return this._currentInternalStep;
  21198. };
  21199. ;
  21200. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21201. get: function () {
  21202. return this._fogEnabled;
  21203. },
  21204. /**
  21205. * is fog enabled on this scene.
  21206. */
  21207. set: function (value) {
  21208. if (this._fogEnabled === value) {
  21209. return;
  21210. }
  21211. this._fogEnabled = value;
  21212. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21213. },
  21214. enumerable: true,
  21215. configurable: true
  21216. });
  21217. Object.defineProperty(Scene.prototype, "fogMode", {
  21218. get: function () {
  21219. return this._fogMode;
  21220. },
  21221. set: function (value) {
  21222. if (this._fogMode === value) {
  21223. return;
  21224. }
  21225. this._fogMode = value;
  21226. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21227. },
  21228. enumerable: true,
  21229. configurable: true
  21230. });
  21231. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21232. get: function () {
  21233. return this._shadowsEnabled;
  21234. },
  21235. set: function (value) {
  21236. if (this._shadowsEnabled === value) {
  21237. return;
  21238. }
  21239. this._shadowsEnabled = value;
  21240. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21241. },
  21242. enumerable: true,
  21243. configurable: true
  21244. });
  21245. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21246. get: function () {
  21247. return this._lightsEnabled;
  21248. },
  21249. set: function (value) {
  21250. if (this._lightsEnabled === value) {
  21251. return;
  21252. }
  21253. this._lightsEnabled = value;
  21254. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21255. },
  21256. enumerable: true,
  21257. configurable: true
  21258. });
  21259. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21260. /** The default material used on meshes when no material is affected */
  21261. get: function () {
  21262. if (!this._defaultMaterial) {
  21263. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21264. }
  21265. return this._defaultMaterial;
  21266. },
  21267. /** The default material used on meshes when no material is affected */
  21268. set: function (value) {
  21269. this._defaultMaterial = value;
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21275. get: function () {
  21276. return this._texturesEnabled;
  21277. },
  21278. set: function (value) {
  21279. if (this._texturesEnabled === value) {
  21280. return;
  21281. }
  21282. this._texturesEnabled = value;
  21283. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21289. get: function () {
  21290. return this._skeletonsEnabled;
  21291. },
  21292. set: function (value) {
  21293. if (this._skeletonsEnabled === value) {
  21294. return;
  21295. }
  21296. this._skeletonsEnabled = value;
  21297. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21298. },
  21299. enumerable: true,
  21300. configurable: true
  21301. });
  21302. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21303. get: function () {
  21304. if (!this._postProcessRenderPipelineManager) {
  21305. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21306. }
  21307. return this._postProcessRenderPipelineManager;
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21313. get: function () {
  21314. if (!this._mainSoundTrack) {
  21315. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21316. }
  21317. return this._mainSoundTrack;
  21318. },
  21319. enumerable: true,
  21320. configurable: true
  21321. });
  21322. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21323. get: function () {
  21324. return this._alternateRendering;
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21330. get: function () {
  21331. return this._frustumPlanes;
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21337. /**
  21338. * Gets the current geometry buffer associated to the scene.
  21339. */
  21340. get: function () {
  21341. return this._geometryBufferRenderer;
  21342. },
  21343. /**
  21344. * Sets the current geometry buffer for the scene.
  21345. */
  21346. set: function (geometryBufferRenderer) {
  21347. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21348. this._geometryBufferRenderer = geometryBufferRenderer;
  21349. }
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Scene.prototype, "debugLayer", {
  21355. // Properties
  21356. get: function () {
  21357. if (!this._debugLayer) {
  21358. this._debugLayer = new BABYLON.DebugLayer(this);
  21359. }
  21360. return this._debugLayer;
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21366. get: function () {
  21367. return this._workerCollisions;
  21368. },
  21369. set: function (enabled) {
  21370. if (!BABYLON.CollisionCoordinatorLegacy) {
  21371. return;
  21372. }
  21373. enabled = (enabled && !!Worker);
  21374. this._workerCollisions = enabled;
  21375. if (this.collisionCoordinator) {
  21376. this.collisionCoordinator.destroy();
  21377. }
  21378. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21379. this.collisionCoordinator.init(this);
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21385. get: function () {
  21386. return this._selectionOctree;
  21387. },
  21388. enumerable: true,
  21389. configurable: true
  21390. });
  21391. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21392. /**
  21393. * The mesh that is currently under the pointer.
  21394. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21395. */
  21396. get: function () {
  21397. return this._pointerOverMesh;
  21398. },
  21399. enumerable: true,
  21400. configurable: true
  21401. });
  21402. Object.defineProperty(Scene.prototype, "pointerX", {
  21403. /**
  21404. * Current on-screen X position of the pointer
  21405. * @return {number} X position of the pointer
  21406. */
  21407. get: function () {
  21408. return this._pointerX;
  21409. },
  21410. enumerable: true,
  21411. configurable: true
  21412. });
  21413. Object.defineProperty(Scene.prototype, "pointerY", {
  21414. /**
  21415. * Current on-screen Y position of the pointer
  21416. * @return {number} Y position of the pointer
  21417. */
  21418. get: function () {
  21419. return this._pointerY;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Scene.prototype.getCachedMaterial = function () {
  21425. return this._cachedMaterial;
  21426. };
  21427. Scene.prototype.getCachedEffect = function () {
  21428. return this._cachedEffect;
  21429. };
  21430. Scene.prototype.getCachedVisibility = function () {
  21431. return this._cachedVisibility;
  21432. };
  21433. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21434. if (visibility === void 0) { visibility = 1; }
  21435. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21436. };
  21437. Scene.prototype.getBoundingBoxRenderer = function () {
  21438. if (!this._boundingBoxRenderer) {
  21439. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21440. }
  21441. return this._boundingBoxRenderer;
  21442. };
  21443. Scene.prototype.getOutlineRenderer = function () {
  21444. return this._outlineRenderer;
  21445. };
  21446. Scene.prototype.getEngine = function () {
  21447. return this._engine;
  21448. };
  21449. Scene.prototype.getTotalVertices = function () {
  21450. return this._totalVertices.current;
  21451. };
  21452. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21453. get: function () {
  21454. return this._totalVertices;
  21455. },
  21456. enumerable: true,
  21457. configurable: true
  21458. });
  21459. Scene.prototype.getActiveIndices = function () {
  21460. return this._activeIndices.current;
  21461. };
  21462. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21463. get: function () {
  21464. return this._activeIndices;
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Scene.prototype.getActiveParticles = function () {
  21470. return this._activeParticles.current;
  21471. };
  21472. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21473. get: function () {
  21474. return this._activeParticles;
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. Scene.prototype.getActiveBones = function () {
  21480. return this._activeBones.current;
  21481. };
  21482. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21483. get: function () {
  21484. return this._activeBones;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. // Stats
  21490. Scene.prototype.getInterFramePerfCounter = function () {
  21491. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21492. return 0;
  21493. };
  21494. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21495. get: function () {
  21496. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21497. return null;
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Scene.prototype.getLastFrameDuration = function () {
  21503. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21504. return 0;
  21505. };
  21506. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21507. get: function () {
  21508. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21509. return null;
  21510. },
  21511. enumerable: true,
  21512. configurable: true
  21513. });
  21514. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21515. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21516. return 0;
  21517. };
  21518. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21519. get: function () {
  21520. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21521. return null;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Scene.prototype.getActiveMeshes = function () {
  21527. return this._activeMeshes;
  21528. };
  21529. Scene.prototype.getRenderTargetsDuration = function () {
  21530. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21531. return 0;
  21532. };
  21533. Scene.prototype.getRenderDuration = function () {
  21534. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21535. return 0;
  21536. };
  21537. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21538. get: function () {
  21539. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21540. return null;
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Scene.prototype.getParticlesDuration = function () {
  21546. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21547. return 0;
  21548. };
  21549. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21550. get: function () {
  21551. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21552. return null;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Scene.prototype.getSpritesDuration = function () {
  21558. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21559. return 0;
  21560. };
  21561. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21562. get: function () {
  21563. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21564. return null;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Scene.prototype.getAnimationRatio = function () {
  21570. return this._animationRatio;
  21571. };
  21572. Scene.prototype.getRenderId = function () {
  21573. return this._renderId;
  21574. };
  21575. Scene.prototype.incrementRenderId = function () {
  21576. this._renderId++;
  21577. };
  21578. Scene.prototype._updatePointerPosition = function (evt) {
  21579. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21580. if (!canvasRect) {
  21581. return;
  21582. }
  21583. this._pointerX = evt.clientX - canvasRect.left;
  21584. this._pointerY = evt.clientY - canvasRect.top;
  21585. this._unTranslatedPointerX = this._pointerX;
  21586. this._unTranslatedPointerY = this._pointerY;
  21587. };
  21588. Scene.prototype._createUbo = function () {
  21589. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21590. this._sceneUbo.addUniform("viewProjection", 16);
  21591. this._sceneUbo.addUniform("view", 16);
  21592. };
  21593. Scene.prototype._createAlternateUbo = function () {
  21594. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21595. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21596. this._alternateSceneUbo.addUniform("view", 16);
  21597. };
  21598. // Pointers handling
  21599. /**
  21600. * Use this method to simulate a pointer move on a mesh
  21601. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21602. */
  21603. Scene.prototype.simulatePointerMove = function (pickResult) {
  21604. var evt = new PointerEvent("pointermove");
  21605. return this._processPointerMove(pickResult, evt);
  21606. };
  21607. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21608. var canvas = this._engine.getRenderingCanvas();
  21609. if (!canvas) {
  21610. return this;
  21611. }
  21612. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21613. this.setPointerOverSprite(null);
  21614. this.setPointerOverMesh(pickResult.pickedMesh);
  21615. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21616. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21617. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21618. }
  21619. else {
  21620. canvas.style.cursor = this.hoverCursor;
  21621. }
  21622. }
  21623. else {
  21624. canvas.style.cursor = this.defaultCursor;
  21625. }
  21626. }
  21627. else {
  21628. this.setPointerOverMesh(null);
  21629. // Sprites
  21630. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21631. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21632. this.setPointerOverSprite(pickResult.pickedSprite);
  21633. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21634. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21635. }
  21636. else {
  21637. canvas.style.cursor = this.hoverCursor;
  21638. }
  21639. }
  21640. else {
  21641. this.setPointerOverSprite(null);
  21642. // Restore pointer
  21643. canvas.style.cursor = this.defaultCursor;
  21644. }
  21645. }
  21646. if (pickResult) {
  21647. if (this.onPointerMove) {
  21648. this.onPointerMove(evt, pickResult);
  21649. }
  21650. if (this.onPointerObservable.hasObservers()) {
  21651. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21652. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21653. this.onPointerObservable.notifyObservers(pi, type);
  21654. }
  21655. }
  21656. return this;
  21657. };
  21658. /**
  21659. * Use this method to simulate a pointer down on a mesh
  21660. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21661. */
  21662. Scene.prototype.simulatePointerDown = function (pickResult) {
  21663. var evt = new PointerEvent("pointerdown");
  21664. return this._processPointerDown(pickResult, evt);
  21665. };
  21666. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21667. var _this = this;
  21668. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21669. this._pickedDownMesh = pickResult.pickedMesh;
  21670. var actionManager = pickResult.pickedMesh.actionManager;
  21671. if (actionManager) {
  21672. if (actionManager.hasPickTriggers) {
  21673. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21674. switch (evt.button) {
  21675. case 0:
  21676. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21677. break;
  21678. case 1:
  21679. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21680. break;
  21681. case 2:
  21682. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21683. break;
  21684. }
  21685. }
  21686. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21687. window.setTimeout(function () {
  21688. 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);
  21689. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21690. if (_this._totalPointersPressed !== 0 &&
  21691. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21692. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21693. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21694. _this._startingPointerTime = 0;
  21695. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21696. }
  21697. }
  21698. }, Scene.LongPressDelay);
  21699. }
  21700. }
  21701. }
  21702. if (pickResult) {
  21703. if (this.onPointerDown) {
  21704. this.onPointerDown(evt, pickResult);
  21705. }
  21706. if (this.onPointerObservable.hasObservers()) {
  21707. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21708. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21709. this.onPointerObservable.notifyObservers(pi, type);
  21710. }
  21711. }
  21712. return this;
  21713. };
  21714. /**
  21715. * Use this method to simulate a pointer up on a mesh
  21716. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21717. */
  21718. Scene.prototype.simulatePointerUp = function (pickResult) {
  21719. var evt = new PointerEvent("pointerup");
  21720. var clickInfo = new ClickInfo();
  21721. clickInfo.singleClick = true;
  21722. clickInfo.ignore = true;
  21723. return this._processPointerUp(pickResult, evt, clickInfo);
  21724. };
  21725. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21726. if (pickResult && pickResult && pickResult.pickedMesh) {
  21727. this._pickedUpMesh = pickResult.pickedMesh;
  21728. if (this._pickedDownMesh === this._pickedUpMesh) {
  21729. if (this.onPointerPick) {
  21730. this.onPointerPick(evt, pickResult);
  21731. }
  21732. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21733. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21734. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21735. this.onPointerObservable.notifyObservers(pi, type);
  21736. }
  21737. }
  21738. if (pickResult.pickedMesh.actionManager) {
  21739. if (clickInfo.ignore) {
  21740. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21741. }
  21742. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21743. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21744. }
  21745. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21746. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21747. }
  21748. }
  21749. }
  21750. if (this._pickedDownMesh &&
  21751. this._pickedDownMesh.actionManager &&
  21752. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21753. this._pickedDownMesh !== this._pickedUpMesh) {
  21754. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21755. }
  21756. if (this.onPointerUp) {
  21757. this.onPointerUp(evt, pickResult);
  21758. }
  21759. if (this.onPointerObservable.hasObservers()) {
  21760. if (!clickInfo.ignore) {
  21761. if (!clickInfo.hasSwiped) {
  21762. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21763. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21764. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21765. this.onPointerObservable.notifyObservers(pi, type);
  21766. }
  21767. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21768. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21769. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21770. this.onPointerObservable.notifyObservers(pi, type);
  21771. }
  21772. }
  21773. }
  21774. else {
  21775. var type = BABYLON.PointerEventTypes.POINTERUP;
  21776. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21777. this.onPointerObservable.notifyObservers(pi, type);
  21778. }
  21779. }
  21780. return this;
  21781. };
  21782. /**
  21783. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21784. * @param attachUp defines if you want to attach events to pointerup
  21785. * @param attachDown defines if you want to attach events to pointerdown
  21786. * @param attachMove defines if you want to attach events to pointermove
  21787. */
  21788. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21789. var _this = this;
  21790. if (attachUp === void 0) { attachUp = true; }
  21791. if (attachDown === void 0) { attachDown = true; }
  21792. if (attachMove === void 0) { attachMove = true; }
  21793. this._initActionManager = function (act, clickInfo) {
  21794. if (!_this._meshPickProceed) {
  21795. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21796. _this._currentPickResult = pickResult;
  21797. if (pickResult) {
  21798. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21799. }
  21800. _this._meshPickProceed = true;
  21801. }
  21802. return act;
  21803. };
  21804. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21805. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21806. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21807. btn !== _this._previousButtonPressed) {
  21808. _this._doubleClickOccured = false;
  21809. clickInfo.singleClick = true;
  21810. clickInfo.ignore = false;
  21811. cb(clickInfo, _this._currentPickResult);
  21812. }
  21813. };
  21814. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21815. var clickInfo = new ClickInfo();
  21816. _this._currentPickResult = null;
  21817. var act = null;
  21818. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21819. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21820. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21821. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21822. act = _this._initActionManager(act, clickInfo);
  21823. if (act)
  21824. checkPicking = act.hasPickTriggers;
  21825. }
  21826. if (checkPicking) {
  21827. var btn = evt.button;
  21828. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21829. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21830. if (!clickInfo.hasSwiped) {
  21831. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21832. if (!checkSingleClickImmediately) {
  21833. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21834. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21835. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21836. act = _this._initActionManager(act, clickInfo);
  21837. if (act)
  21838. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21839. }
  21840. }
  21841. if (checkSingleClickImmediately) {
  21842. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21843. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21844. btn !== _this._previousButtonPressed) {
  21845. clickInfo.singleClick = true;
  21846. cb(clickInfo, _this._currentPickResult);
  21847. }
  21848. }
  21849. else {
  21850. // wait that no double click has been raised during the double click delay
  21851. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21852. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21853. }
  21854. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21855. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21856. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21857. act = _this._initActionManager(act, clickInfo);
  21858. if (act)
  21859. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21860. }
  21861. if (checkDoubleClick) {
  21862. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21863. if (btn === _this._previousButtonPressed &&
  21864. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21865. !_this._doubleClickOccured) {
  21866. // pointer has not moved for 2 clicks, it's a double click
  21867. if (!clickInfo.hasSwiped &&
  21868. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21869. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21870. _this._previousStartingPointerTime = 0;
  21871. _this._doubleClickOccured = true;
  21872. clickInfo.doubleClick = true;
  21873. clickInfo.ignore = false;
  21874. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21875. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21876. }
  21877. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21878. cb(clickInfo, _this._currentPickResult);
  21879. }
  21880. else {
  21881. _this._doubleClickOccured = false;
  21882. _this._previousStartingPointerTime = _this._startingPointerTime;
  21883. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21884. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21885. _this._previousButtonPressed = btn;
  21886. if (Scene.ExclusiveDoubleClickMode) {
  21887. if (_this._previousDelayedSimpleClickTimeout) {
  21888. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21889. }
  21890. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21891. cb(clickInfo, _this._previousPickResult);
  21892. }
  21893. else {
  21894. cb(clickInfo, _this._currentPickResult);
  21895. }
  21896. }
  21897. }
  21898. else {
  21899. _this._doubleClickOccured = false;
  21900. _this._previousStartingPointerTime = _this._startingPointerTime;
  21901. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21902. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21903. _this._previousButtonPressed = btn;
  21904. }
  21905. }
  21906. }
  21907. }
  21908. clickInfo.ignore = true;
  21909. cb(clickInfo, _this._currentPickResult);
  21910. };
  21911. this._spritePredicate = function (sprite) {
  21912. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21913. };
  21914. this._onPointerMove = function (evt) {
  21915. _this._updatePointerPosition(evt);
  21916. // PreObservable support
  21917. if (_this.onPrePointerObservable.hasObservers()) {
  21918. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21919. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21920. _this.onPrePointerObservable.notifyObservers(pi, type);
  21921. if (pi.skipOnPointerObservable) {
  21922. return;
  21923. }
  21924. }
  21925. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21926. return;
  21927. }
  21928. if (!_this.pointerMovePredicate) {
  21929. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21930. }
  21931. // Meshes
  21932. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21933. _this._processPointerMove(pickResult, evt);
  21934. };
  21935. this._onPointerDown = function (evt) {
  21936. _this._totalPointersPressed++;
  21937. _this._pickedDownMesh = null;
  21938. _this._meshPickProceed = false;
  21939. _this._updatePointerPosition(evt);
  21940. if (_this.preventDefaultOnPointerDown && canvas) {
  21941. evt.preventDefault();
  21942. canvas.focus();
  21943. }
  21944. // PreObservable support
  21945. if (_this.onPrePointerObservable.hasObservers()) {
  21946. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21947. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21948. _this.onPrePointerObservable.notifyObservers(pi, type);
  21949. if (pi.skipOnPointerObservable) {
  21950. return;
  21951. }
  21952. }
  21953. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21954. return;
  21955. }
  21956. _this._startingPointerPosition.x = _this._pointerX;
  21957. _this._startingPointerPosition.y = _this._pointerY;
  21958. _this._startingPointerTime = new Date().getTime();
  21959. if (!_this.pointerDownPredicate) {
  21960. _this.pointerDownPredicate = function (mesh) {
  21961. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21962. };
  21963. }
  21964. // Meshes
  21965. _this._pickedDownMesh = null;
  21966. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21967. _this._processPointerDown(pickResult, evt);
  21968. // Sprites
  21969. _this._pickedDownSprite = null;
  21970. if (_this.spriteManagers.length > 0) {
  21971. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21972. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21973. if (pickResult.pickedSprite.actionManager) {
  21974. _this._pickedDownSprite = pickResult.pickedSprite;
  21975. switch (evt.button) {
  21976. case 0:
  21977. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21978. break;
  21979. case 1:
  21980. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21981. break;
  21982. case 2:
  21983. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21984. break;
  21985. }
  21986. if (pickResult.pickedSprite.actionManager) {
  21987. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21988. }
  21989. }
  21990. }
  21991. }
  21992. };
  21993. this._onPointerUp = function (evt) {
  21994. if (_this._totalPointersPressed === 0) {
  21995. return; // So we need to test it the pointer down was pressed before.
  21996. }
  21997. _this._totalPointersPressed--;
  21998. _this._pickedUpMesh = null;
  21999. _this._meshPickProceed = false;
  22000. _this._updatePointerPosition(evt);
  22001. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22002. // PreObservable support
  22003. if (_this.onPrePointerObservable.hasObservers()) {
  22004. if (!clickInfo.ignore) {
  22005. if (!clickInfo.hasSwiped) {
  22006. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22007. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22008. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22009. _this.onPrePointerObservable.notifyObservers(pi, type);
  22010. if (pi.skipOnPointerObservable) {
  22011. return;
  22012. }
  22013. }
  22014. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22015. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22016. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22017. _this.onPrePointerObservable.notifyObservers(pi, type);
  22018. if (pi.skipOnPointerObservable) {
  22019. return;
  22020. }
  22021. }
  22022. }
  22023. }
  22024. else {
  22025. var type = BABYLON.PointerEventTypes.POINTERUP;
  22026. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22027. _this.onPrePointerObservable.notifyObservers(pi, type);
  22028. if (pi.skipOnPointerObservable) {
  22029. return;
  22030. }
  22031. }
  22032. }
  22033. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22034. return;
  22035. }
  22036. if (!_this.pointerUpPredicate) {
  22037. _this.pointerUpPredicate = function (mesh) {
  22038. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22039. };
  22040. }
  22041. // Meshes
  22042. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22043. _this._initActionManager(null, clickInfo);
  22044. }
  22045. if (!pickResult) {
  22046. pickResult = _this._currentPickResult;
  22047. }
  22048. _this._processPointerUp(pickResult, evt, clickInfo);
  22049. // Sprites
  22050. if (_this.spriteManagers.length > 0) {
  22051. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22052. if (spritePickResult) {
  22053. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22054. if (spritePickResult.pickedSprite.actionManager) {
  22055. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22056. if (spritePickResult.pickedSprite.actionManager) {
  22057. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22058. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22059. }
  22060. }
  22061. }
  22062. }
  22063. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22064. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22065. }
  22066. }
  22067. }
  22068. _this._previousPickResult = _this._currentPickResult;
  22069. });
  22070. };
  22071. this._onKeyDown = function (evt) {
  22072. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22073. if (_this.onPreKeyboardObservable.hasObservers()) {
  22074. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22075. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22076. if (pi.skipOnPointerObservable) {
  22077. return;
  22078. }
  22079. }
  22080. if (_this.onKeyboardObservable.hasObservers()) {
  22081. var pi = new BABYLON.KeyboardInfo(type, evt);
  22082. _this.onKeyboardObservable.notifyObservers(pi, type);
  22083. }
  22084. if (_this.actionManager) {
  22085. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22086. }
  22087. };
  22088. this._onKeyUp = function (evt) {
  22089. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22090. if (_this.onPreKeyboardObservable.hasObservers()) {
  22091. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22092. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22093. if (pi.skipOnPointerObservable) {
  22094. return;
  22095. }
  22096. }
  22097. if (_this.onKeyboardObservable.hasObservers()) {
  22098. var pi = new BABYLON.KeyboardInfo(type, evt);
  22099. _this.onKeyboardObservable.notifyObservers(pi, type);
  22100. }
  22101. if (_this.actionManager) {
  22102. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22103. }
  22104. };
  22105. var engine = this.getEngine();
  22106. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22107. if (!canvas) {
  22108. return;
  22109. }
  22110. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22111. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22112. });
  22113. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22114. if (!canvas) {
  22115. return;
  22116. }
  22117. canvas.removeEventListener("keydown", _this._onKeyDown);
  22118. canvas.removeEventListener("keyup", _this._onKeyUp);
  22119. });
  22120. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22121. var canvas = this._engine.getRenderingCanvas();
  22122. if (!canvas) {
  22123. return;
  22124. }
  22125. if (attachMove) {
  22126. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22127. // Wheel
  22128. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22129. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22130. }
  22131. if (attachDown) {
  22132. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22133. }
  22134. if (attachUp) {
  22135. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22136. }
  22137. canvas.tabIndex = 1;
  22138. };
  22139. Scene.prototype.detachControl = function () {
  22140. var engine = this.getEngine();
  22141. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22142. var canvas = engine.getRenderingCanvas();
  22143. if (!canvas) {
  22144. return;
  22145. }
  22146. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22147. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22148. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22149. if (this._onCanvasBlurObserver) {
  22150. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22151. }
  22152. if (this._onCanvasFocusObserver) {
  22153. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22154. }
  22155. // Wheel
  22156. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22157. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22158. // Keyboard
  22159. canvas.removeEventListener("keydown", this._onKeyDown);
  22160. canvas.removeEventListener("keyup", this._onKeyUp);
  22161. // Observables
  22162. this.onKeyboardObservable.clear();
  22163. this.onPreKeyboardObservable.clear();
  22164. this.onPointerObservable.clear();
  22165. this.onPrePointerObservable.clear();
  22166. };
  22167. /**
  22168. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22169. * Delay loaded resources are not taking in account
  22170. * @return true if all required resources are ready
  22171. */
  22172. Scene.prototype.isReady = function () {
  22173. if (this._isDisposed) {
  22174. return false;
  22175. }
  22176. if (this._pendingData.length > 0) {
  22177. return false;
  22178. }
  22179. var index;
  22180. var engine = this.getEngine();
  22181. // Geometries
  22182. for (index = 0; index < this._geometries.length; index++) {
  22183. var geometry = this._geometries[index];
  22184. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22185. return false;
  22186. }
  22187. }
  22188. // Meshes
  22189. for (index = 0; index < this.meshes.length; index++) {
  22190. var mesh = this.meshes[index];
  22191. if (!mesh.isEnabled()) {
  22192. continue;
  22193. }
  22194. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22195. continue;
  22196. }
  22197. if (!mesh.isReady()) {
  22198. return false;
  22199. }
  22200. // Effect layers
  22201. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22202. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22203. var layer = _a[_i];
  22204. if (!layer.hasMesh(mesh)) {
  22205. continue;
  22206. }
  22207. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22208. var subMesh = _c[_b];
  22209. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22210. return false;
  22211. }
  22212. }
  22213. }
  22214. }
  22215. return true;
  22216. };
  22217. Scene.prototype.resetCachedMaterial = function () {
  22218. this._cachedMaterial = null;
  22219. this._cachedEffect = null;
  22220. this._cachedVisibility = null;
  22221. };
  22222. Scene.prototype.registerBeforeRender = function (func) {
  22223. this.onBeforeRenderObservable.add(func);
  22224. };
  22225. Scene.prototype.unregisterBeforeRender = function (func) {
  22226. this.onBeforeRenderObservable.removeCallback(func);
  22227. };
  22228. Scene.prototype.registerAfterRender = function (func) {
  22229. this.onAfterRenderObservable.add(func);
  22230. };
  22231. Scene.prototype.unregisterAfterRender = function (func) {
  22232. this.onAfterRenderObservable.removeCallback(func);
  22233. };
  22234. Scene.prototype._executeOnceBeforeRender = function (func) {
  22235. var _this = this;
  22236. var execFunc = function () {
  22237. func();
  22238. setTimeout(function () {
  22239. _this.unregisterBeforeRender(execFunc);
  22240. });
  22241. };
  22242. this.registerBeforeRender(execFunc);
  22243. };
  22244. /**
  22245. * The provided function will run before render once and will be disposed afterwards.
  22246. * A timeout delay can be provided so that the function will be executed in N ms.
  22247. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22248. * @param func The function to be executed.
  22249. * @param timeout optional delay in ms
  22250. */
  22251. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22252. var _this = this;
  22253. if (timeout !== undefined) {
  22254. setTimeout(function () {
  22255. _this._executeOnceBeforeRender(func);
  22256. }, timeout);
  22257. }
  22258. else {
  22259. this._executeOnceBeforeRender(func);
  22260. }
  22261. };
  22262. Scene.prototype._addPendingData = function (data) {
  22263. this._pendingData.push(data);
  22264. };
  22265. Scene.prototype._removePendingData = function (data) {
  22266. var wasLoading = this.isLoading;
  22267. var index = this._pendingData.indexOf(data);
  22268. if (index !== -1) {
  22269. this._pendingData.splice(index, 1);
  22270. }
  22271. if (wasLoading && !this.isLoading) {
  22272. this.onDataLoadedObservable.notifyObservers(this);
  22273. }
  22274. };
  22275. Scene.prototype.getWaitingItemsCount = function () {
  22276. return this._pendingData.length;
  22277. };
  22278. Object.defineProperty(Scene.prototype, "isLoading", {
  22279. get: function () {
  22280. return this._pendingData.length > 0;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. /**
  22286. * Registers a function to be executed when the scene is ready.
  22287. * @param {Function} func - the function to be executed.
  22288. */
  22289. Scene.prototype.executeWhenReady = function (func) {
  22290. var _this = this;
  22291. this.onReadyObservable.add(func);
  22292. if (this._executeWhenReadyTimeoutId !== -1) {
  22293. return;
  22294. }
  22295. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22296. _this._checkIsReady();
  22297. }, 150);
  22298. };
  22299. /**
  22300. * Returns a promise that resolves when the scene is ready.
  22301. * @returns A promise that resolves when the scene is ready.
  22302. */
  22303. Scene.prototype.whenReadyAsync = function () {
  22304. var _this = this;
  22305. return new Promise(function (resolve) {
  22306. _this.executeWhenReady(function () {
  22307. resolve();
  22308. });
  22309. });
  22310. };
  22311. Scene.prototype._checkIsReady = function () {
  22312. var _this = this;
  22313. if (this.isReady()) {
  22314. this.onReadyObservable.notifyObservers(this);
  22315. this.onReadyObservable.clear();
  22316. this._executeWhenReadyTimeoutId = -1;
  22317. return;
  22318. }
  22319. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22320. _this._checkIsReady();
  22321. }, 150);
  22322. };
  22323. // Animations
  22324. /**
  22325. * Will start the animation sequence of a given target
  22326. * @param target - the target
  22327. * @param {number} from - from which frame should animation start
  22328. * @param {number} to - till which frame should animation run.
  22329. * @param {boolean} [loop] - should the animation loop
  22330. * @param {number} [speedRatio] - the speed in which to run the animation
  22331. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22332. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22333. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22334. * See BABYLON.Animatable
  22335. */
  22336. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22337. if (speedRatio === void 0) { speedRatio = 1.0; }
  22338. if (from > to && speedRatio > 0) {
  22339. speedRatio *= -1;
  22340. }
  22341. this.stopAnimation(target);
  22342. if (!animatable) {
  22343. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22344. }
  22345. // Local animations
  22346. if (target.animations) {
  22347. animatable.appendAnimations(target, target.animations);
  22348. }
  22349. // Children animations
  22350. if (target.getAnimatables) {
  22351. var animatables = target.getAnimatables();
  22352. for (var index = 0; index < animatables.length; index++) {
  22353. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22354. }
  22355. }
  22356. animatable.reset();
  22357. return animatable;
  22358. };
  22359. /**
  22360. * Begin a new animation on a given node
  22361. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22362. * @param {BABYLON.Animation[]} defines the list of animations to start
  22363. * @param {number} from defines the initial value
  22364. * @param {number} to defines the final value
  22365. * @param {boolean} loop defines if you want animation to loop (off by default)
  22366. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22367. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22368. * @returns the list of created animatables
  22369. */
  22370. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22371. if (speedRatio === undefined) {
  22372. speedRatio = 1.0;
  22373. }
  22374. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22375. return animatable;
  22376. };
  22377. /**
  22378. * Begin a new animation on a given node and its hierarchy
  22379. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22380. * @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.
  22381. * @param {BABYLON.Animation[]} defines the list of animations to start
  22382. * @param {number} from defines the initial value
  22383. * @param {number} to defines the final value
  22384. * @param {boolean} loop defines if you want animation to loop (off by default)
  22385. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22386. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22387. * @returns the list of animatables created for all nodes
  22388. */
  22389. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22390. var children = target.getDescendants(directDescendantsOnly);
  22391. var result = [];
  22392. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22393. var child = children_1[_i];
  22394. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22395. }
  22396. return result;
  22397. };
  22398. Scene.prototype.getAnimatableByTarget = function (target) {
  22399. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22400. if (this._activeAnimatables[index].target === target) {
  22401. return this._activeAnimatables[index];
  22402. }
  22403. }
  22404. return null;
  22405. };
  22406. Object.defineProperty(Scene.prototype, "animatables", {
  22407. get: function () {
  22408. return this._activeAnimatables;
  22409. },
  22410. enumerable: true,
  22411. configurable: true
  22412. });
  22413. /**
  22414. * Will stop the animation of the given target
  22415. * @param target - the target
  22416. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22417. * @see beginAnimation
  22418. */
  22419. Scene.prototype.stopAnimation = function (target, animationName) {
  22420. var animatable = this.getAnimatableByTarget(target);
  22421. if (animatable) {
  22422. animatable.stop(animationName);
  22423. }
  22424. };
  22425. /**
  22426. * Stops and removes all animations that have been applied to the scene
  22427. */
  22428. Scene.prototype.stopAllAnimations = function () {
  22429. if (this._activeAnimatables) {
  22430. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22431. this._activeAnimatables[i].stop();
  22432. }
  22433. this._activeAnimatables = [];
  22434. }
  22435. };
  22436. Scene.prototype._animate = function () {
  22437. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22438. return;
  22439. }
  22440. // Getting time
  22441. var now = BABYLON.Tools.Now;
  22442. if (!this._animationTimeLast) {
  22443. if (this._pendingData.length > 0) {
  22444. return;
  22445. }
  22446. this._animationTimeLast = now;
  22447. }
  22448. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22449. this._animationTime += deltaTime;
  22450. this._animationTimeLast = now;
  22451. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22452. this._activeAnimatables[index]._animate(this._animationTime);
  22453. }
  22454. };
  22455. // Matrix
  22456. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22457. this._useAlternateCameraConfiguration = active;
  22458. };
  22459. Scene.prototype.getViewMatrix = function () {
  22460. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22461. };
  22462. Scene.prototype.getProjectionMatrix = function () {
  22463. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22464. };
  22465. Scene.prototype.getTransformMatrix = function () {
  22466. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22467. };
  22468. Scene.prototype.setTransformMatrix = function (view, projection) {
  22469. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22470. return;
  22471. }
  22472. this._viewUpdateFlag = view.updateFlag;
  22473. this._projectionUpdateFlag = projection.updateFlag;
  22474. this._viewMatrix = view;
  22475. this._projectionMatrix = projection;
  22476. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22477. // Update frustum
  22478. if (!this._frustumPlanes) {
  22479. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22480. }
  22481. else {
  22482. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22483. }
  22484. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22485. var otherCamera = this.activeCamera._alternateCamera;
  22486. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22487. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22488. }
  22489. if (this._sceneUbo.useUbo) {
  22490. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22491. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22492. this._sceneUbo.update();
  22493. }
  22494. };
  22495. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22496. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22497. return;
  22498. }
  22499. this._alternateViewUpdateFlag = view.updateFlag;
  22500. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22501. this._alternateViewMatrix = view;
  22502. this._alternateProjectionMatrix = projection;
  22503. if (!this._alternateTransformMatrix) {
  22504. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22505. }
  22506. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22507. if (!this._alternateSceneUbo) {
  22508. this._createAlternateUbo();
  22509. }
  22510. if (this._alternateSceneUbo.useUbo) {
  22511. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22512. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22513. this._alternateSceneUbo.update();
  22514. }
  22515. };
  22516. Scene.prototype.getSceneUniformBuffer = function () {
  22517. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22518. };
  22519. // Methods
  22520. Scene.prototype.getUniqueId = function () {
  22521. var result = Scene._uniqueIdCounter;
  22522. Scene._uniqueIdCounter++;
  22523. return result;
  22524. };
  22525. Scene.prototype.addMesh = function (newMesh) {
  22526. this.meshes.push(newMesh);
  22527. //notify the collision coordinator
  22528. if (this.collisionCoordinator) {
  22529. this.collisionCoordinator.onMeshAdded(newMesh);
  22530. }
  22531. newMesh._resyncLightSources();
  22532. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22533. };
  22534. Scene.prototype.removeMesh = function (toRemove) {
  22535. var index = this.meshes.indexOf(toRemove);
  22536. if (index !== -1) {
  22537. // Remove from the scene if mesh found
  22538. this.meshes.splice(index, 1);
  22539. }
  22540. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22541. return index;
  22542. };
  22543. Scene.prototype.addTransformNode = function (newTransformNode) {
  22544. this.transformNodes.push(newTransformNode);
  22545. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22546. };
  22547. Scene.prototype.removeTransformNode = function (toRemove) {
  22548. var index = this.transformNodes.indexOf(toRemove);
  22549. if (index !== -1) {
  22550. // Remove from the scene if found
  22551. this.transformNodes.splice(index, 1);
  22552. }
  22553. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22554. return index;
  22555. };
  22556. Scene.prototype.removeSkeleton = function (toRemove) {
  22557. var index = this.skeletons.indexOf(toRemove);
  22558. if (index !== -1) {
  22559. // Remove from the scene if found
  22560. this.skeletons.splice(index, 1);
  22561. }
  22562. return index;
  22563. };
  22564. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22565. var index = this.morphTargetManagers.indexOf(toRemove);
  22566. if (index !== -1) {
  22567. // Remove from the scene if found
  22568. this.morphTargetManagers.splice(index, 1);
  22569. }
  22570. return index;
  22571. };
  22572. Scene.prototype.removeLight = function (toRemove) {
  22573. var index = this.lights.indexOf(toRemove);
  22574. if (index !== -1) {
  22575. // Remove from meshes
  22576. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22577. var mesh = _a[_i];
  22578. mesh._removeLightSource(toRemove);
  22579. }
  22580. // Remove from the scene if mesh found
  22581. this.lights.splice(index, 1);
  22582. this.sortLightsByPriority();
  22583. }
  22584. this.onLightRemovedObservable.notifyObservers(toRemove);
  22585. return index;
  22586. };
  22587. Scene.prototype.removeCamera = function (toRemove) {
  22588. var index = this.cameras.indexOf(toRemove);
  22589. if (index !== -1) {
  22590. // Remove from the scene if mesh found
  22591. this.cameras.splice(index, 1);
  22592. }
  22593. // Remove from activeCameras
  22594. var index2 = this.activeCameras.indexOf(toRemove);
  22595. if (index2 !== -1) {
  22596. // Remove from the scene if mesh found
  22597. this.activeCameras.splice(index2, 1);
  22598. }
  22599. // Reset the activeCamera
  22600. if (this.activeCamera === toRemove) {
  22601. if (this.cameras.length > 0) {
  22602. this.activeCamera = this.cameras[0];
  22603. }
  22604. else {
  22605. this.activeCamera = null;
  22606. }
  22607. }
  22608. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22609. return index;
  22610. };
  22611. Scene.prototype.removeParticleSystem = function (toRemove) {
  22612. var index = this.particleSystems.indexOf(toRemove);
  22613. if (index !== -1) {
  22614. this.particleSystems.splice(index, 1);
  22615. }
  22616. return index;
  22617. };
  22618. ;
  22619. Scene.prototype.removeAnimation = function (toRemove) {
  22620. var index = this.animations.indexOf(toRemove);
  22621. if (index !== -1) {
  22622. this.animations.splice(index, 1);
  22623. }
  22624. return index;
  22625. };
  22626. ;
  22627. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22628. var index = this.multiMaterials.indexOf(toRemove);
  22629. if (index !== -1) {
  22630. this.multiMaterials.splice(index, 1);
  22631. }
  22632. return index;
  22633. };
  22634. ;
  22635. Scene.prototype.removeMaterial = function (toRemove) {
  22636. var index = this.materials.indexOf(toRemove);
  22637. if (index !== -1) {
  22638. this.materials.splice(index, 1);
  22639. }
  22640. return index;
  22641. };
  22642. ;
  22643. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22644. var index = this.lensFlareSystems.indexOf(toRemove);
  22645. if (index !== -1) {
  22646. this.lensFlareSystems.splice(index, 1);
  22647. }
  22648. return index;
  22649. };
  22650. ;
  22651. Scene.prototype.removeActionManager = function (toRemove) {
  22652. var index = this._actionManagers.indexOf(toRemove);
  22653. if (index !== -1) {
  22654. this._actionManagers.splice(index, 1);
  22655. }
  22656. return index;
  22657. };
  22658. ;
  22659. Scene.prototype.addLight = function (newLight) {
  22660. this.lights.push(newLight);
  22661. this.sortLightsByPriority();
  22662. // Add light to all meshes (To support if the light is removed and then readded)
  22663. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22664. var mesh = _a[_i];
  22665. if (mesh._lightSources.indexOf(newLight) === -1) {
  22666. mesh._lightSources.push(newLight);
  22667. mesh._resyncLightSources();
  22668. }
  22669. }
  22670. this.onNewLightAddedObservable.notifyObservers(newLight);
  22671. };
  22672. Scene.prototype.sortLightsByPriority = function () {
  22673. if (this.requireLightSorting) {
  22674. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22675. }
  22676. };
  22677. Scene.prototype.addCamera = function (newCamera) {
  22678. this.cameras.push(newCamera);
  22679. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22680. };
  22681. Scene.prototype.addSkeleton = function (newSkeleton) {
  22682. this.skeletons.push(newSkeleton);
  22683. };
  22684. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22685. this.particleSystems.push(newParticleSystem);
  22686. };
  22687. Scene.prototype.addAnimation = function (newAnimation) {
  22688. this.animations.push(newAnimation);
  22689. };
  22690. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22691. this.multiMaterials.push(newMultiMaterial);
  22692. };
  22693. Scene.prototype.addMaterial = function (newMaterial) {
  22694. this.materials.push(newMaterial);
  22695. };
  22696. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22697. this.morphTargetManagers.push(newMorphTargetManager);
  22698. };
  22699. Scene.prototype.addGeometry = function (newGeometrie) {
  22700. this._geometries.push(newGeometrie);
  22701. };
  22702. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22703. this.lensFlareSystems.push(newLensFlareSystem);
  22704. };
  22705. Scene.prototype.addActionManager = function (newActionManager) {
  22706. this._actionManagers.push(newActionManager);
  22707. };
  22708. /**
  22709. * Switch active camera
  22710. * @param {Camera} newCamera - new active camera
  22711. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22712. */
  22713. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22714. if (attachControl === void 0) { attachControl = true; }
  22715. var canvas = this._engine.getRenderingCanvas();
  22716. if (!canvas) {
  22717. return;
  22718. }
  22719. if (this.activeCamera) {
  22720. this.activeCamera.detachControl(canvas);
  22721. }
  22722. this.activeCamera = newCamera;
  22723. if (attachControl) {
  22724. newCamera.attachControl(canvas);
  22725. }
  22726. };
  22727. /**
  22728. * sets the active camera of the scene using its ID
  22729. * @param {string} id - the camera's ID
  22730. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22731. * @see activeCamera
  22732. */
  22733. Scene.prototype.setActiveCameraByID = function (id) {
  22734. var camera = this.getCameraByID(id);
  22735. if (camera) {
  22736. this.activeCamera = camera;
  22737. return camera;
  22738. }
  22739. return null;
  22740. };
  22741. /**
  22742. * sets the active camera of the scene using its name
  22743. * @param {string} name - the camera's name
  22744. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22745. * @see activeCamera
  22746. */
  22747. Scene.prototype.setActiveCameraByName = function (name) {
  22748. var camera = this.getCameraByName(name);
  22749. if (camera) {
  22750. this.activeCamera = camera;
  22751. return camera;
  22752. }
  22753. return null;
  22754. };
  22755. /**
  22756. * get an animation group using its name
  22757. * @param {string} the material's name
  22758. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22759. */
  22760. Scene.prototype.getAnimationGroupByName = function (name) {
  22761. for (var index = 0; index < this.animationGroups.length; index++) {
  22762. if (this.animationGroups[index].name === name) {
  22763. return this.animationGroups[index];
  22764. }
  22765. }
  22766. return null;
  22767. };
  22768. /**
  22769. * get a material using its id
  22770. * @param {string} the material's ID
  22771. * @return {BABYLON.Material|null} the material or null if none found.
  22772. */
  22773. Scene.prototype.getMaterialByID = function (id) {
  22774. for (var index = 0; index < this.materials.length; index++) {
  22775. if (this.materials[index].id === id) {
  22776. return this.materials[index];
  22777. }
  22778. }
  22779. return null;
  22780. };
  22781. /**
  22782. * get a material using its name
  22783. * @param {string} the material's name
  22784. * @return {BABYLON.Material|null} the material or null if none found.
  22785. */
  22786. Scene.prototype.getMaterialByName = function (name) {
  22787. for (var index = 0; index < this.materials.length; index++) {
  22788. if (this.materials[index].name === name) {
  22789. return this.materials[index];
  22790. }
  22791. }
  22792. return null;
  22793. };
  22794. Scene.prototype.getLensFlareSystemByName = function (name) {
  22795. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22796. if (this.lensFlareSystems[index].name === name) {
  22797. return this.lensFlareSystems[index];
  22798. }
  22799. }
  22800. return null;
  22801. };
  22802. Scene.prototype.getLensFlareSystemByID = function (id) {
  22803. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22804. if (this.lensFlareSystems[index].id === id) {
  22805. return this.lensFlareSystems[index];
  22806. }
  22807. }
  22808. return null;
  22809. };
  22810. Scene.prototype.getCameraByID = function (id) {
  22811. for (var index = 0; index < this.cameras.length; index++) {
  22812. if (this.cameras[index].id === id) {
  22813. return this.cameras[index];
  22814. }
  22815. }
  22816. return null;
  22817. };
  22818. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22819. for (var index = 0; index < this.cameras.length; index++) {
  22820. if (this.cameras[index].uniqueId === uniqueId) {
  22821. return this.cameras[index];
  22822. }
  22823. }
  22824. return null;
  22825. };
  22826. /**
  22827. * get a camera using its name
  22828. * @param {string} the camera's name
  22829. * @return {BABYLON.Camera|null} the camera or null if none found.
  22830. */
  22831. Scene.prototype.getCameraByName = function (name) {
  22832. for (var index = 0; index < this.cameras.length; index++) {
  22833. if (this.cameras[index].name === name) {
  22834. return this.cameras[index];
  22835. }
  22836. }
  22837. return null;
  22838. };
  22839. /**
  22840. * get a bone using its id
  22841. * @param {string} the bone's id
  22842. * @return {BABYLON.Bone|null} the bone or null if not found
  22843. */
  22844. Scene.prototype.getBoneByID = function (id) {
  22845. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22846. var skeleton = this.skeletons[skeletonIndex];
  22847. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22848. if (skeleton.bones[boneIndex].id === id) {
  22849. return skeleton.bones[boneIndex];
  22850. }
  22851. }
  22852. }
  22853. return null;
  22854. };
  22855. /**
  22856. * get a bone using its id
  22857. * @param {string} the bone's name
  22858. * @return {BABYLON.Bone|null} the bone or null if not found
  22859. */
  22860. Scene.prototype.getBoneByName = function (name) {
  22861. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22862. var skeleton = this.skeletons[skeletonIndex];
  22863. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22864. if (skeleton.bones[boneIndex].name === name) {
  22865. return skeleton.bones[boneIndex];
  22866. }
  22867. }
  22868. }
  22869. return null;
  22870. };
  22871. /**
  22872. * get a light node using its name
  22873. * @param {string} the light's name
  22874. * @return {BABYLON.Light|null} the light or null if none found.
  22875. */
  22876. Scene.prototype.getLightByName = function (name) {
  22877. for (var index = 0; index < this.lights.length; index++) {
  22878. if (this.lights[index].name === name) {
  22879. return this.lights[index];
  22880. }
  22881. }
  22882. return null;
  22883. };
  22884. /**
  22885. * get a light node using its ID
  22886. * @param {string} the light's id
  22887. * @return {BABYLON.Light|null} the light or null if none found.
  22888. */
  22889. Scene.prototype.getLightByID = function (id) {
  22890. for (var index = 0; index < this.lights.length; index++) {
  22891. if (this.lights[index].id === id) {
  22892. return this.lights[index];
  22893. }
  22894. }
  22895. return null;
  22896. };
  22897. /**
  22898. * get a light node using its scene-generated unique ID
  22899. * @param {number} the light's unique id
  22900. * @return {BABYLON.Light|null} the light or null if none found.
  22901. */
  22902. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22903. for (var index = 0; index < this.lights.length; index++) {
  22904. if (this.lights[index].uniqueId === uniqueId) {
  22905. return this.lights[index];
  22906. }
  22907. }
  22908. return null;
  22909. };
  22910. /**
  22911. * get a particle system by id
  22912. * @param id {number} the particle system id
  22913. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22914. */
  22915. Scene.prototype.getParticleSystemByID = function (id) {
  22916. for (var index = 0; index < this.particleSystems.length; index++) {
  22917. if (this.particleSystems[index].id === id) {
  22918. return this.particleSystems[index];
  22919. }
  22920. }
  22921. return null;
  22922. };
  22923. /**
  22924. * get a geometry using its ID
  22925. * @param {string} the geometry's id
  22926. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22927. */
  22928. Scene.prototype.getGeometryByID = function (id) {
  22929. for (var index = 0; index < this._geometries.length; index++) {
  22930. if (this._geometries[index].id === id) {
  22931. return this._geometries[index];
  22932. }
  22933. }
  22934. return null;
  22935. };
  22936. /**
  22937. * add a new geometry to this scene.
  22938. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22939. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22940. * @return {boolean} was the geometry added or not
  22941. */
  22942. Scene.prototype.pushGeometry = function (geometry, force) {
  22943. if (!force && this.getGeometryByID(geometry.id)) {
  22944. return false;
  22945. }
  22946. this._geometries.push(geometry);
  22947. //notify the collision coordinator
  22948. if (this.collisionCoordinator) {
  22949. this.collisionCoordinator.onGeometryAdded(geometry);
  22950. }
  22951. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22952. return true;
  22953. };
  22954. /**
  22955. * Removes an existing geometry
  22956. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22957. * @return {boolean} was the geometry removed or not
  22958. */
  22959. Scene.prototype.removeGeometry = function (geometry) {
  22960. var index = this._geometries.indexOf(geometry);
  22961. if (index > -1) {
  22962. this._geometries.splice(index, 1);
  22963. //notify the collision coordinator
  22964. if (this.collisionCoordinator) {
  22965. this.collisionCoordinator.onGeometryDeleted(geometry);
  22966. }
  22967. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22968. return true;
  22969. }
  22970. return false;
  22971. };
  22972. Scene.prototype.getGeometries = function () {
  22973. return this._geometries;
  22974. };
  22975. /**
  22976. * Get the first added mesh found of a given ID
  22977. * @param {string} id - the id to search for
  22978. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22979. */
  22980. Scene.prototype.getMeshByID = function (id) {
  22981. for (var index = 0; index < this.meshes.length; index++) {
  22982. if (this.meshes[index].id === id) {
  22983. return this.meshes[index];
  22984. }
  22985. }
  22986. return null;
  22987. };
  22988. Scene.prototype.getMeshesByID = function (id) {
  22989. return this.meshes.filter(function (m) {
  22990. return m.id === id;
  22991. });
  22992. };
  22993. /**
  22994. * Get the first added transform node found of a given ID
  22995. * @param {string} id - the id to search for
  22996. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22997. */
  22998. Scene.prototype.getTransformNodeByID = function (id) {
  22999. for (var index = 0; index < this.transformNodes.length; index++) {
  23000. if (this.transformNodes[index].id === id) {
  23001. return this.transformNodes[index];
  23002. }
  23003. }
  23004. return null;
  23005. };
  23006. Scene.prototype.getTransformNodesByID = function (id) {
  23007. return this.transformNodes.filter(function (m) {
  23008. return m.id === id;
  23009. });
  23010. };
  23011. /**
  23012. * Get a mesh with its auto-generated unique id
  23013. * @param {number} uniqueId - the unique id to search for
  23014. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23015. */
  23016. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23017. for (var index = 0; index < this.meshes.length; index++) {
  23018. if (this.meshes[index].uniqueId === uniqueId) {
  23019. return this.meshes[index];
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. /**
  23025. * Get a the last added mesh found of a given ID
  23026. * @param {string} id - the id to search for
  23027. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23028. */
  23029. Scene.prototype.getLastMeshByID = function (id) {
  23030. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23031. if (this.meshes[index].id === id) {
  23032. return this.meshes[index];
  23033. }
  23034. }
  23035. return null;
  23036. };
  23037. /**
  23038. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23039. * @param {string} id - the id to search for
  23040. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23041. */
  23042. Scene.prototype.getLastEntryByID = function (id) {
  23043. var index;
  23044. for (index = this.meshes.length - 1; index >= 0; index--) {
  23045. if (this.meshes[index].id === id) {
  23046. return this.meshes[index];
  23047. }
  23048. }
  23049. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23050. if (this.transformNodes[index].id === id) {
  23051. return this.transformNodes[index];
  23052. }
  23053. }
  23054. for (index = this.cameras.length - 1; index >= 0; index--) {
  23055. if (this.cameras[index].id === id) {
  23056. return this.cameras[index];
  23057. }
  23058. }
  23059. for (index = this.lights.length - 1; index >= 0; index--) {
  23060. if (this.lights[index].id === id) {
  23061. return this.lights[index];
  23062. }
  23063. }
  23064. return null;
  23065. };
  23066. Scene.prototype.getNodeByID = function (id) {
  23067. var mesh = this.getMeshByID(id);
  23068. if (mesh) {
  23069. return mesh;
  23070. }
  23071. var light = this.getLightByID(id);
  23072. if (light) {
  23073. return light;
  23074. }
  23075. var camera = this.getCameraByID(id);
  23076. if (camera) {
  23077. return camera;
  23078. }
  23079. var bone = this.getBoneByID(id);
  23080. return bone;
  23081. };
  23082. Scene.prototype.getNodeByName = function (name) {
  23083. var mesh = this.getMeshByName(name);
  23084. if (mesh) {
  23085. return mesh;
  23086. }
  23087. var light = this.getLightByName(name);
  23088. if (light) {
  23089. return light;
  23090. }
  23091. var camera = this.getCameraByName(name);
  23092. if (camera) {
  23093. return camera;
  23094. }
  23095. var bone = this.getBoneByName(name);
  23096. return bone;
  23097. };
  23098. Scene.prototype.getMeshByName = function (name) {
  23099. for (var index = 0; index < this.meshes.length; index++) {
  23100. if (this.meshes[index].name === name) {
  23101. return this.meshes[index];
  23102. }
  23103. }
  23104. return null;
  23105. };
  23106. Scene.prototype.getTransformNodeByName = function (name) {
  23107. for (var index = 0; index < this.transformNodes.length; index++) {
  23108. if (this.transformNodes[index].name === name) {
  23109. return this.transformNodes[index];
  23110. }
  23111. }
  23112. return null;
  23113. };
  23114. Scene.prototype.getSoundByName = function (name) {
  23115. var index;
  23116. if (BABYLON.AudioEngine) {
  23117. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23118. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23119. return this.mainSoundTrack.soundCollection[index];
  23120. }
  23121. }
  23122. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23123. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23124. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23125. return this.soundTracks[sdIndex].soundCollection[index];
  23126. }
  23127. }
  23128. }
  23129. }
  23130. return null;
  23131. };
  23132. Scene.prototype.getLastSkeletonByID = function (id) {
  23133. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23134. if (this.skeletons[index].id === id) {
  23135. return this.skeletons[index];
  23136. }
  23137. }
  23138. return null;
  23139. };
  23140. Scene.prototype.getSkeletonById = function (id) {
  23141. for (var index = 0; index < this.skeletons.length; index++) {
  23142. if (this.skeletons[index].id === id) {
  23143. return this.skeletons[index];
  23144. }
  23145. }
  23146. return null;
  23147. };
  23148. Scene.prototype.getSkeletonByName = function (name) {
  23149. for (var index = 0; index < this.skeletons.length; index++) {
  23150. if (this.skeletons[index].name === name) {
  23151. return this.skeletons[index];
  23152. }
  23153. }
  23154. return null;
  23155. };
  23156. Scene.prototype.getMorphTargetManagerById = function (id) {
  23157. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23158. if (this.morphTargetManagers[index].uniqueId === id) {
  23159. return this.morphTargetManagers[index];
  23160. }
  23161. }
  23162. return null;
  23163. };
  23164. Scene.prototype.isActiveMesh = function (mesh) {
  23165. return (this._activeMeshes.indexOf(mesh) !== -1);
  23166. };
  23167. /**
  23168. * Return a the first highlight layer of the scene with a given name.
  23169. * @param name The name of the highlight layer to look for.
  23170. * @return The highlight layer if found otherwise null.
  23171. */
  23172. Scene.prototype.getHighlightLayerByName = function (name) {
  23173. for (var index = 0; index < this.effectLayers.length; index++) {
  23174. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23175. return this.effectLayers[index];
  23176. }
  23177. }
  23178. return null;
  23179. };
  23180. /**
  23181. * Return a the first highlight layer of the scene with a given name.
  23182. * @param name The name of the highlight layer to look for.
  23183. * @return The highlight layer if found otherwise null.
  23184. */
  23185. Scene.prototype.getGlowLayerByName = function (name) {
  23186. for (var index = 0; index < this.effectLayers.length; index++) {
  23187. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23188. return this.effectLayers[index];
  23189. }
  23190. }
  23191. return null;
  23192. };
  23193. Object.defineProperty(Scene.prototype, "uid", {
  23194. /**
  23195. * Return a unique id as a string which can serve as an identifier for the scene
  23196. */
  23197. get: function () {
  23198. if (!this._uid) {
  23199. this._uid = BABYLON.Tools.RandomId();
  23200. }
  23201. return this._uid;
  23202. },
  23203. enumerable: true,
  23204. configurable: true
  23205. });
  23206. /**
  23207. * Add an externaly attached data from its key.
  23208. * This method call will fail and return false, if such key already exists.
  23209. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23210. * @param key the unique key that identifies the data
  23211. * @param data the data object to associate to the key for this Engine instance
  23212. * @return true if no such key were already present and the data was added successfully, false otherwise
  23213. */
  23214. Scene.prototype.addExternalData = function (key, data) {
  23215. if (!this._externalData) {
  23216. this._externalData = new BABYLON.StringDictionary();
  23217. }
  23218. return this._externalData.add(key, data);
  23219. };
  23220. /**
  23221. * Get an externaly attached data from its key
  23222. * @param key the unique key that identifies the data
  23223. * @return the associated data, if present (can be null), or undefined if not present
  23224. */
  23225. Scene.prototype.getExternalData = function (key) {
  23226. if (!this._externalData) {
  23227. return null;
  23228. }
  23229. return this._externalData.get(key);
  23230. };
  23231. /**
  23232. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23233. * @param key the unique key that identifies the data
  23234. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23235. * @return the associated data, can be null if the factory returned null.
  23236. */
  23237. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23238. if (!this._externalData) {
  23239. this._externalData = new BABYLON.StringDictionary();
  23240. }
  23241. return this._externalData.getOrAddWithFactory(key, factory);
  23242. };
  23243. /**
  23244. * Remove an externaly attached data from the Engine instance
  23245. * @param key the unique key that identifies the data
  23246. * @return true if the data was successfully removed, false if it doesn't exist
  23247. */
  23248. Scene.prototype.removeExternalData = function (key) {
  23249. return this._externalData.remove(key);
  23250. };
  23251. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23252. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23253. if (mesh.showSubMeshesBoundingBox) {
  23254. var boundingInfo = subMesh.getBoundingInfo();
  23255. if (boundingInfo !== null && boundingInfo !== undefined) {
  23256. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23257. }
  23258. }
  23259. var material = subMesh.getMaterial();
  23260. if (material !== null && material !== undefined) {
  23261. // Render targets
  23262. if (material.getRenderTargetTextures !== undefined) {
  23263. if (this._processedMaterials.indexOf(material) === -1) {
  23264. this._processedMaterials.push(material);
  23265. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23266. }
  23267. }
  23268. // Dispatch
  23269. this._activeIndices.addCount(subMesh.indexCount, false);
  23270. this._renderingManager.dispatch(subMesh, mesh, material);
  23271. }
  23272. }
  23273. };
  23274. Scene.prototype._isInIntermediateRendering = function () {
  23275. return this._intermediateRendering;
  23276. };
  23277. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23278. this._activeMeshCandidateProvider = provider;
  23279. };
  23280. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23281. return this._activeMeshCandidateProvider;
  23282. };
  23283. /**
  23284. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23285. */
  23286. Scene.prototype.freezeActiveMeshes = function () {
  23287. this._evaluateActiveMeshes();
  23288. this._activeMeshesFrozen = true;
  23289. return this;
  23290. };
  23291. /**
  23292. * Use this function to restart evaluating active meshes on every frame
  23293. */
  23294. Scene.prototype.unfreezeActiveMeshes = function () {
  23295. this._activeMeshesFrozen = false;
  23296. return this;
  23297. };
  23298. Scene.prototype._evaluateActiveMeshes = function () {
  23299. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23300. return;
  23301. }
  23302. if (!this.activeCamera) {
  23303. return;
  23304. }
  23305. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23306. this.activeCamera._activeMeshes.reset();
  23307. this._activeMeshes.reset();
  23308. this._renderingManager.reset();
  23309. this._processedMaterials.reset();
  23310. this._activeParticleSystems.reset();
  23311. this._activeSkeletons.reset();
  23312. this._softwareSkinnedMeshes.reset();
  23313. if (this._boundingBoxRenderer) {
  23314. this._boundingBoxRenderer.reset();
  23315. }
  23316. // Meshes
  23317. var meshes;
  23318. var len;
  23319. var checkIsEnabled = true;
  23320. // Determine mesh candidates
  23321. if (this._activeMeshCandidateProvider !== undefined) {
  23322. // Use _activeMeshCandidateProvider
  23323. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23324. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23325. if (meshes !== undefined) {
  23326. len = meshes.length;
  23327. }
  23328. else {
  23329. len = 0;
  23330. }
  23331. }
  23332. else if (this._selectionOctree !== undefined) {
  23333. // Octree
  23334. var selection = this._selectionOctree.select(this._frustumPlanes);
  23335. meshes = selection.data;
  23336. len = selection.length;
  23337. }
  23338. else {
  23339. // Full scene traversal
  23340. len = this.meshes.length;
  23341. meshes = this.meshes;
  23342. }
  23343. // Check each mesh
  23344. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23345. mesh = meshes[meshIndex];
  23346. if (mesh.isBlocked) {
  23347. continue;
  23348. }
  23349. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23350. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23351. continue;
  23352. }
  23353. mesh.computeWorldMatrix();
  23354. // Intersections
  23355. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23356. this._meshesForIntersections.pushNoDuplicate(mesh);
  23357. }
  23358. // Switch to current LOD
  23359. meshLOD = mesh.getLOD(this.activeCamera);
  23360. if (meshLOD === undefined || meshLOD === null) {
  23361. continue;
  23362. }
  23363. mesh._preActivate();
  23364. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23365. this._activeMeshes.push(mesh);
  23366. this.activeCamera._activeMeshes.push(mesh);
  23367. mesh._activate(this._renderId);
  23368. if (meshLOD !== mesh) {
  23369. meshLOD._activate(this._renderId);
  23370. }
  23371. this._activeMesh(mesh, meshLOD);
  23372. }
  23373. }
  23374. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23375. // Particle systems
  23376. if (this.particlesEnabled) {
  23377. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23378. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23379. var particleSystem = this.particleSystems[particleIndex];
  23380. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23381. continue;
  23382. }
  23383. var emitter = particleSystem.emitter;
  23384. if (!emitter.position || emitter.isEnabled()) {
  23385. this._activeParticleSystems.push(particleSystem);
  23386. particleSystem.animate();
  23387. this._renderingManager.dispatchParticles(particleSystem);
  23388. }
  23389. }
  23390. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23391. }
  23392. };
  23393. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23394. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23395. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23396. mesh.skeleton.prepare();
  23397. }
  23398. if (!mesh.computeBonesUsingShaders) {
  23399. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23400. }
  23401. }
  23402. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23403. var boundingInfo = sourceMesh.getBoundingInfo();
  23404. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23405. }
  23406. if (mesh !== undefined && mesh !== null
  23407. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23408. // Submeshes Octrees
  23409. var len;
  23410. var subMeshes;
  23411. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23412. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23413. len = intersections.length;
  23414. subMeshes = intersections.data;
  23415. }
  23416. else {
  23417. subMeshes = mesh.subMeshes;
  23418. len = subMeshes.length;
  23419. }
  23420. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23421. subMesh = subMeshes[subIndex];
  23422. this._evaluateSubMesh(subMesh, mesh);
  23423. }
  23424. }
  23425. };
  23426. Scene.prototype.updateTransformMatrix = function (force) {
  23427. if (!this.activeCamera) {
  23428. return;
  23429. }
  23430. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23431. };
  23432. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23433. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23434. };
  23435. Scene.prototype._renderForCamera = function (camera) {
  23436. if (camera && camera._skipRendering) {
  23437. return;
  23438. }
  23439. var engine = this._engine;
  23440. this.activeCamera = camera;
  23441. if (!this.activeCamera)
  23442. throw new Error("Active camera not set");
  23443. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23444. // Viewport
  23445. engine.setViewport(this.activeCamera.viewport);
  23446. // Camera
  23447. this.resetCachedMaterial();
  23448. this._renderId++;
  23449. this.activeCamera.update();
  23450. this.updateTransformMatrix();
  23451. if (camera._alternateCamera) {
  23452. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23453. this._alternateRendering = true;
  23454. }
  23455. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23456. // Meshes
  23457. this._evaluateActiveMeshes();
  23458. // Software skinning
  23459. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23460. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23461. mesh.applySkeleton(mesh.skeleton);
  23462. }
  23463. // Render targets
  23464. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23465. var needsRestoreFrameBuffer = false;
  23466. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23467. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23468. }
  23469. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23470. this._intermediateRendering = true;
  23471. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23472. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23473. var renderTarget = this._renderTargets.data[renderIndex];
  23474. if (renderTarget._shouldRender()) {
  23475. this._renderId++;
  23476. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23477. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23478. }
  23479. }
  23480. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23481. this._intermediateRendering = false;
  23482. this._renderId++;
  23483. needsRestoreFrameBuffer = true; // Restore back buffer
  23484. }
  23485. // Render EffecttLayer Texture
  23486. var stencilState = this._engine.getStencilBuffer();
  23487. var renderEffects = false;
  23488. var needStencil = false;
  23489. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23490. this._intermediateRendering = true;
  23491. for (var i = 0; i < this.effectLayers.length; i++) {
  23492. var effectLayer = this.effectLayers[i];
  23493. if (effectLayer.shouldRender() &&
  23494. (!effectLayer.camera ||
  23495. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23496. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23497. renderEffects = true;
  23498. needStencil = needStencil || effectLayer.needStencil();
  23499. var renderTarget = effectLayer._mainTexture;
  23500. if (renderTarget._shouldRender()) {
  23501. this._renderId++;
  23502. renderTarget.render(false, false);
  23503. needsRestoreFrameBuffer = true;
  23504. }
  23505. }
  23506. }
  23507. this._intermediateRendering = false;
  23508. this._renderId++;
  23509. }
  23510. if (needsRestoreFrameBuffer) {
  23511. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23512. }
  23513. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23514. // Prepare Frame
  23515. this.postProcessManager._prepareFrame();
  23516. // Backgrounds
  23517. var layerIndex;
  23518. var layer;
  23519. if (this.layers.length) {
  23520. engine.setDepthBuffer(false);
  23521. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23522. layer = this.layers[layerIndex];
  23523. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23524. layer.render();
  23525. }
  23526. }
  23527. engine.setDepthBuffer(true);
  23528. }
  23529. // Activate effect Layer stencil
  23530. if (needStencil) {
  23531. this._engine.setStencilBuffer(true);
  23532. }
  23533. // Render
  23534. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23535. this._renderingManager.render(null, null, true, true);
  23536. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23537. // Restore effect Layer stencil
  23538. if (needStencil) {
  23539. this._engine.setStencilBuffer(stencilState);
  23540. }
  23541. // Bounding boxes
  23542. if (this._boundingBoxRenderer) {
  23543. this._boundingBoxRenderer.render();
  23544. }
  23545. // Lens flares
  23546. if (this.lensFlaresEnabled) {
  23547. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23548. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23549. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23550. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23551. lensFlareSystem.render();
  23552. }
  23553. }
  23554. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23555. }
  23556. // Foregrounds
  23557. if (this.layers.length) {
  23558. engine.setDepthBuffer(false);
  23559. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23560. layer = this.layers[layerIndex];
  23561. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23562. layer.render();
  23563. }
  23564. }
  23565. engine.setDepthBuffer(true);
  23566. }
  23567. // Effect Layer
  23568. if (renderEffects) {
  23569. engine.setDepthBuffer(false);
  23570. for (var i = 0; i < this.effectLayers.length; i++) {
  23571. if (this.effectLayers[i].shouldRender()) {
  23572. this.effectLayers[i].render();
  23573. }
  23574. }
  23575. engine.setDepthBuffer(true);
  23576. }
  23577. // Finalize frame
  23578. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23579. // Reset some special arrays
  23580. this._renderTargets.reset();
  23581. this._alternateRendering = false;
  23582. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23583. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23584. };
  23585. Scene.prototype._processSubCameras = function (camera) {
  23586. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23587. this._renderForCamera(camera);
  23588. return;
  23589. }
  23590. // Update camera
  23591. if (this.activeCamera) {
  23592. this.activeCamera.update();
  23593. }
  23594. // rig cameras
  23595. for (var index = 0; index < camera._rigCameras.length; index++) {
  23596. this._renderForCamera(camera._rigCameras[index]);
  23597. }
  23598. this.activeCamera = camera;
  23599. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23600. };
  23601. Scene.prototype._checkIntersections = function () {
  23602. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23603. var sourceMesh = this._meshesForIntersections.data[index];
  23604. if (!sourceMesh.actionManager) {
  23605. continue;
  23606. }
  23607. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23608. var action = sourceMesh.actionManager.actions[actionIndex];
  23609. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23610. var parameters = action.getTriggerParameter();
  23611. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23612. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23613. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23614. if (areIntersecting && currentIntersectionInProgress === -1) {
  23615. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23616. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23617. sourceMesh._intersectionsInProgress.push(otherMesh);
  23618. }
  23619. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23620. sourceMesh._intersectionsInProgress.push(otherMesh);
  23621. }
  23622. }
  23623. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23624. //They intersected, and now they don't.
  23625. //is this trigger an exit trigger? execute an event.
  23626. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23627. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23628. }
  23629. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23630. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23631. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23632. }
  23633. }
  23634. }
  23635. }
  23636. }
  23637. };
  23638. Scene.prototype.render = function () {
  23639. if (this.isDisposed) {
  23640. return;
  23641. }
  23642. this._activeParticles.fetchNewFrame();
  23643. this._totalVertices.fetchNewFrame();
  23644. this._activeIndices.fetchNewFrame();
  23645. this._activeBones.fetchNewFrame();
  23646. this._meshesForIntersections.reset();
  23647. this.resetCachedMaterial();
  23648. this.onBeforeAnimationsObservable.notifyObservers(this);
  23649. // Actions
  23650. if (this.actionManager) {
  23651. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23652. }
  23653. //Simplification Queue
  23654. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23655. this.simplificationQueue.executeNext();
  23656. }
  23657. if (this._engine.isDeterministicLockStep()) {
  23658. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23659. var defaultFPS = (60.0 / 1000.0);
  23660. var defaultFrameTime = 1000 / 60; // frame time in MS
  23661. if (this._physicsEngine) {
  23662. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23663. }
  23664. var stepsTaken = 0;
  23665. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23666. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23667. internalSteps = Math.min(internalSteps, maxSubSteps);
  23668. do {
  23669. this.onBeforeStepObservable.notifyObservers(this);
  23670. // Animations
  23671. this._animationRatio = defaultFrameTime * defaultFPS;
  23672. this._animate();
  23673. this.onAfterAnimationsObservable.notifyObservers(this);
  23674. // Physics
  23675. if (this._physicsEngine) {
  23676. this.onBeforePhysicsObservable.notifyObservers(this);
  23677. this._physicsEngine._step(defaultFrameTime / 1000);
  23678. this.onAfterPhysicsObservable.notifyObservers(this);
  23679. }
  23680. this.onAfterStepObservable.notifyObservers(this);
  23681. this._currentStepId++;
  23682. stepsTaken++;
  23683. deltaTime -= defaultFrameTime;
  23684. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23685. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23686. }
  23687. else {
  23688. // Animations
  23689. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23690. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23691. this._animate();
  23692. this.onAfterAnimationsObservable.notifyObservers(this);
  23693. // Physics
  23694. if (this._physicsEngine) {
  23695. this.onBeforePhysicsObservable.notifyObservers(this);
  23696. this._physicsEngine._step(deltaTime / 1000.0);
  23697. this.onAfterPhysicsObservable.notifyObservers(this);
  23698. }
  23699. }
  23700. // update gamepad manager
  23701. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23702. this._gamepadManager._checkGamepadsStatus();
  23703. }
  23704. // Before render
  23705. this.onBeforeRenderObservable.notifyObservers(this);
  23706. // Customs render targets
  23707. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23708. var engine = this.getEngine();
  23709. var currentActiveCamera = this.activeCamera;
  23710. if (this.renderTargetsEnabled) {
  23711. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23712. this._intermediateRendering = true;
  23713. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23714. var renderTarget = this.customRenderTargets[customIndex];
  23715. if (renderTarget._shouldRender()) {
  23716. this._renderId++;
  23717. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23718. if (!this.activeCamera)
  23719. throw new Error("Active camera not set");
  23720. // Viewport
  23721. engine.setViewport(this.activeCamera.viewport);
  23722. // Camera
  23723. this.updateTransformMatrix();
  23724. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23725. }
  23726. }
  23727. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23728. this._intermediateRendering = false;
  23729. this._renderId++;
  23730. }
  23731. // Restore back buffer
  23732. if (this.customRenderTargets.length > 0) {
  23733. engine.restoreDefaultFramebuffer();
  23734. }
  23735. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23736. this.activeCamera = currentActiveCamera;
  23737. // Procedural textures
  23738. if (this.proceduralTexturesEnabled) {
  23739. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23740. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23741. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23742. if (proceduralTexture._shouldRender()) {
  23743. proceduralTexture.render();
  23744. }
  23745. }
  23746. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23747. }
  23748. // Clear
  23749. if (this.autoClearDepthAndStencil || this.autoClear) {
  23750. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23751. }
  23752. // Shadows
  23753. if (this.shadowsEnabled) {
  23754. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23755. var light = this.lights[lightIndex];
  23756. var shadowGenerator = light.getShadowGenerator();
  23757. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23758. var shadowMap = (shadowGenerator.getShadowMap());
  23759. if (this.textures.indexOf(shadowMap) !== -1) {
  23760. this._renderTargets.push(shadowMap);
  23761. }
  23762. }
  23763. }
  23764. }
  23765. // Depth renderer
  23766. if (this._depthRenderer) {
  23767. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23768. }
  23769. // Geometry renderer
  23770. if (this._geometryBufferRenderer) {
  23771. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23772. }
  23773. // RenderPipeline
  23774. if (this._postProcessRenderPipelineManager) {
  23775. this._postProcessRenderPipelineManager.update();
  23776. }
  23777. // Multi-cameras?
  23778. if (this.activeCameras.length > 0) {
  23779. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23780. if (cameraIndex > 0) {
  23781. this._engine.clear(null, false, true, true);
  23782. }
  23783. this._processSubCameras(this.activeCameras[cameraIndex]);
  23784. }
  23785. }
  23786. else {
  23787. if (!this.activeCamera) {
  23788. throw new Error("No camera defined");
  23789. }
  23790. this._processSubCameras(this.activeCamera);
  23791. }
  23792. // Intersection checks
  23793. this._checkIntersections();
  23794. // Update the audio listener attached to the camera
  23795. if (BABYLON.AudioEngine) {
  23796. this._updateAudioParameters();
  23797. }
  23798. // After render
  23799. if (this.afterRender) {
  23800. this.afterRender();
  23801. }
  23802. this.onAfterRenderObservable.notifyObservers(this);
  23803. // Cleaning
  23804. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23805. var data = this._toBeDisposed.data[index];
  23806. if (data) {
  23807. data.dispose();
  23808. }
  23809. this._toBeDisposed[index] = null;
  23810. }
  23811. this._toBeDisposed.reset();
  23812. if (this.dumpNextRenderTargets) {
  23813. this.dumpNextRenderTargets = false;
  23814. }
  23815. this._activeBones.addCount(0, true);
  23816. this._activeIndices.addCount(0, true);
  23817. this._activeParticles.addCount(0, true);
  23818. };
  23819. Scene.prototype._updateAudioParameters = function () {
  23820. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23821. return;
  23822. }
  23823. var listeningCamera;
  23824. var audioEngine = BABYLON.Engine.audioEngine;
  23825. if (this.activeCameras.length > 0) {
  23826. listeningCamera = this.activeCameras[0];
  23827. }
  23828. else {
  23829. listeningCamera = this.activeCamera;
  23830. }
  23831. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23832. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23833. // for VR cameras
  23834. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23835. listeningCamera = listeningCamera.rigCameras[0];
  23836. }
  23837. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23838. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23839. cameraDirection.normalize();
  23840. // To avoid some errors on GearVR
  23841. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23842. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23843. }
  23844. var i;
  23845. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23846. var sound = this.mainSoundTrack.soundCollection[i];
  23847. if (sound.useCustomAttenuation) {
  23848. sound.updateDistanceFromListener();
  23849. }
  23850. }
  23851. for (i = 0; i < this.soundTracks.length; i++) {
  23852. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23853. sound = this.soundTracks[i].soundCollection[j];
  23854. if (sound.useCustomAttenuation) {
  23855. sound.updateDistanceFromListener();
  23856. }
  23857. }
  23858. }
  23859. }
  23860. };
  23861. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23862. // Audio
  23863. get: function () {
  23864. return this._audioEnabled;
  23865. },
  23866. set: function (value) {
  23867. this._audioEnabled = value;
  23868. if (BABYLON.AudioEngine) {
  23869. if (this._audioEnabled) {
  23870. this._enableAudio();
  23871. }
  23872. else {
  23873. this._disableAudio();
  23874. }
  23875. }
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Scene.prototype._disableAudio = function () {
  23881. var i;
  23882. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23883. this.mainSoundTrack.soundCollection[i].pause();
  23884. }
  23885. for (i = 0; i < this.soundTracks.length; i++) {
  23886. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23887. this.soundTracks[i].soundCollection[j].pause();
  23888. }
  23889. }
  23890. };
  23891. Scene.prototype._enableAudio = function () {
  23892. var i;
  23893. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23894. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23895. this.mainSoundTrack.soundCollection[i].play();
  23896. }
  23897. }
  23898. for (i = 0; i < this.soundTracks.length; i++) {
  23899. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23900. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23901. this.soundTracks[i].soundCollection[j].play();
  23902. }
  23903. }
  23904. }
  23905. };
  23906. Object.defineProperty(Scene.prototype, "headphone", {
  23907. get: function () {
  23908. return this._headphone;
  23909. },
  23910. set: function (value) {
  23911. this._headphone = value;
  23912. if (BABYLON.AudioEngine) {
  23913. if (this._headphone) {
  23914. this._switchAudioModeForHeadphones();
  23915. }
  23916. else {
  23917. this._switchAudioModeForNormalSpeakers();
  23918. }
  23919. }
  23920. },
  23921. enumerable: true,
  23922. configurable: true
  23923. });
  23924. Scene.prototype._switchAudioModeForHeadphones = function () {
  23925. this.mainSoundTrack.switchPanningModelToHRTF();
  23926. for (var i = 0; i < this.soundTracks.length; i++) {
  23927. this.soundTracks[i].switchPanningModelToHRTF();
  23928. }
  23929. };
  23930. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23931. this.mainSoundTrack.switchPanningModelToEqualPower();
  23932. for (var i = 0; i < this.soundTracks.length; i++) {
  23933. this.soundTracks[i].switchPanningModelToEqualPower();
  23934. }
  23935. };
  23936. Scene.prototype.enableDepthRenderer = function () {
  23937. if (this._depthRenderer) {
  23938. return this._depthRenderer;
  23939. }
  23940. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23941. return this._depthRenderer;
  23942. };
  23943. Scene.prototype.disableDepthRenderer = function () {
  23944. if (!this._depthRenderer) {
  23945. return;
  23946. }
  23947. this._depthRenderer.dispose();
  23948. this._depthRenderer = null;
  23949. };
  23950. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23951. if (ratio === void 0) { ratio = 1; }
  23952. if (this._geometryBufferRenderer) {
  23953. return this._geometryBufferRenderer;
  23954. }
  23955. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23956. if (!this._geometryBufferRenderer.isSupported) {
  23957. this._geometryBufferRenderer = null;
  23958. }
  23959. return this._geometryBufferRenderer;
  23960. };
  23961. Scene.prototype.disableGeometryBufferRenderer = function () {
  23962. if (!this._geometryBufferRenderer) {
  23963. return;
  23964. }
  23965. this._geometryBufferRenderer.dispose();
  23966. this._geometryBufferRenderer = null;
  23967. };
  23968. Scene.prototype.freezeMaterials = function () {
  23969. for (var i = 0; i < this.materials.length; i++) {
  23970. this.materials[i].freeze();
  23971. }
  23972. };
  23973. Scene.prototype.unfreezeMaterials = function () {
  23974. for (var i = 0; i < this.materials.length; i++) {
  23975. this.materials[i].unfreeze();
  23976. }
  23977. };
  23978. Scene.prototype.dispose = function () {
  23979. this.beforeRender = null;
  23980. this.afterRender = null;
  23981. this.skeletons = [];
  23982. this.morphTargetManagers = [];
  23983. this.importedMeshesFiles = new Array();
  23984. this.stopAllAnimations();
  23985. this.resetCachedMaterial();
  23986. if (this._depthRenderer) {
  23987. this._depthRenderer.dispose();
  23988. }
  23989. if (this._gamepadManager) {
  23990. this._gamepadManager.dispose();
  23991. this._gamepadManager = null;
  23992. }
  23993. // Smart arrays
  23994. if (this.activeCamera) {
  23995. this.activeCamera._activeMeshes.dispose();
  23996. this.activeCamera = null;
  23997. }
  23998. this._activeMeshes.dispose();
  23999. this._renderingManager.dispose();
  24000. this._processedMaterials.dispose();
  24001. this._activeParticleSystems.dispose();
  24002. this._activeSkeletons.dispose();
  24003. this._softwareSkinnedMeshes.dispose();
  24004. this._renderTargets.dispose();
  24005. if (this._boundingBoxRenderer) {
  24006. this._boundingBoxRenderer.dispose();
  24007. }
  24008. this._meshesForIntersections.dispose();
  24009. this._toBeDisposed.dispose();
  24010. // Abort active requests
  24011. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24012. var request = _a[_i];
  24013. request.abort();
  24014. }
  24015. // Debug layer
  24016. if (this._debugLayer) {
  24017. this._debugLayer.hide();
  24018. }
  24019. // Events
  24020. this.onDisposeObservable.notifyObservers(this);
  24021. this.onDisposeObservable.clear();
  24022. this.onBeforeRenderObservable.clear();
  24023. this.onAfterRenderObservable.clear();
  24024. this.OnBeforeRenderTargetsRenderObservable.clear();
  24025. this.OnAfterRenderTargetsRenderObservable.clear();
  24026. this.onAfterStepObservable.clear();
  24027. this.onBeforeStepObservable.clear();
  24028. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24029. this.onAfterActiveMeshesEvaluationObservable.clear();
  24030. this.onBeforeParticlesRenderingObservable.clear();
  24031. this.onAfterParticlesRenderingObservable.clear();
  24032. this.onBeforeSpritesRenderingObservable.clear();
  24033. this.onAfterSpritesRenderingObservable.clear();
  24034. this.onBeforeDrawPhaseObservable.clear();
  24035. this.onAfterDrawPhaseObservable.clear();
  24036. this.onBeforePhysicsObservable.clear();
  24037. this.onAfterPhysicsObservable.clear();
  24038. this.onBeforeAnimationsObservable.clear();
  24039. this.onAfterAnimationsObservable.clear();
  24040. this.onDataLoadedObservable.clear();
  24041. this.detachControl();
  24042. // Release sounds & sounds tracks
  24043. if (BABYLON.AudioEngine) {
  24044. this.disposeSounds();
  24045. }
  24046. // VR Helper
  24047. if (this.VRHelper) {
  24048. this.VRHelper.dispose();
  24049. }
  24050. // Detach cameras
  24051. var canvas = this._engine.getRenderingCanvas();
  24052. if (canvas) {
  24053. var index;
  24054. for (index = 0; index < this.cameras.length; index++) {
  24055. this.cameras[index].detachControl(canvas);
  24056. }
  24057. }
  24058. // Release animation groups
  24059. while (this.animationGroups.length) {
  24060. this.animationGroups[0].dispose();
  24061. }
  24062. // Release lights
  24063. while (this.lights.length) {
  24064. this.lights[0].dispose();
  24065. }
  24066. // Release meshes
  24067. while (this.meshes.length) {
  24068. this.meshes[0].dispose(true);
  24069. }
  24070. while (this.transformNodes.length) {
  24071. this.removeTransformNode(this.transformNodes[0]);
  24072. }
  24073. // Release cameras
  24074. while (this.cameras.length) {
  24075. this.cameras[0].dispose();
  24076. }
  24077. // Release materials
  24078. if (this.defaultMaterial) {
  24079. this.defaultMaterial.dispose();
  24080. }
  24081. while (this.multiMaterials.length) {
  24082. this.multiMaterials[0].dispose();
  24083. }
  24084. while (this.materials.length) {
  24085. this.materials[0].dispose();
  24086. }
  24087. // Release particles
  24088. while (this.particleSystems.length) {
  24089. this.particleSystems[0].dispose();
  24090. }
  24091. // Release sprites
  24092. while (this.spriteManagers.length) {
  24093. this.spriteManagers[0].dispose();
  24094. }
  24095. // Release postProcesses
  24096. while (this.postProcesses.length) {
  24097. this.postProcesses[0].dispose();
  24098. }
  24099. // Release layers
  24100. while (this.layers.length) {
  24101. this.layers[0].dispose();
  24102. }
  24103. while (this.effectLayers.length) {
  24104. this.effectLayers[0].dispose();
  24105. }
  24106. // Release textures
  24107. while (this.textures.length) {
  24108. this.textures[0].dispose();
  24109. }
  24110. // Release UBO
  24111. this._sceneUbo.dispose();
  24112. if (this._alternateSceneUbo) {
  24113. this._alternateSceneUbo.dispose();
  24114. }
  24115. // Post-processes
  24116. this.postProcessManager.dispose();
  24117. if (this._postProcessRenderPipelineManager) {
  24118. this._postProcessRenderPipelineManager.dispose();
  24119. }
  24120. // Physics
  24121. if (this._physicsEngine) {
  24122. this.disablePhysicsEngine();
  24123. }
  24124. // Remove from engine
  24125. index = this._engine.scenes.indexOf(this);
  24126. if (index > -1) {
  24127. this._engine.scenes.splice(index, 1);
  24128. }
  24129. this._engine.wipeCaches(true);
  24130. this._isDisposed = true;
  24131. };
  24132. Object.defineProperty(Scene.prototype, "isDisposed", {
  24133. get: function () {
  24134. return this._isDisposed;
  24135. },
  24136. enumerable: true,
  24137. configurable: true
  24138. });
  24139. // Release sounds & sounds tracks
  24140. Scene.prototype.disposeSounds = function () {
  24141. if (!this._mainSoundTrack) {
  24142. return;
  24143. }
  24144. this.mainSoundTrack.dispose();
  24145. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24146. this.soundTracks[scIndex].dispose();
  24147. }
  24148. };
  24149. // Octrees
  24150. Scene.prototype.getWorldExtends = function () {
  24151. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24152. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24153. for (var index = 0; index < this.meshes.length; index++) {
  24154. var mesh = this.meshes[index];
  24155. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24156. continue;
  24157. }
  24158. mesh.computeWorldMatrix(true);
  24159. var boundingInfo = mesh.getBoundingInfo();
  24160. var minBox = boundingInfo.boundingBox.minimumWorld;
  24161. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24162. BABYLON.Tools.CheckExtends(minBox, min, max);
  24163. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24164. }
  24165. return {
  24166. min: min,
  24167. max: max
  24168. };
  24169. };
  24170. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24171. if (maxCapacity === void 0) { maxCapacity = 64; }
  24172. if (maxDepth === void 0) { maxDepth = 2; }
  24173. if (!this._selectionOctree) {
  24174. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24175. }
  24176. var worldExtends = this.getWorldExtends();
  24177. // Update octree
  24178. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24179. return this._selectionOctree;
  24180. };
  24181. // Picking
  24182. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24183. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24184. var result = BABYLON.Ray.Zero();
  24185. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24186. return result;
  24187. };
  24188. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24189. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24190. var engine = this._engine;
  24191. if (!camera) {
  24192. if (!this.activeCamera)
  24193. throw new Error("Active camera not set");
  24194. camera = this.activeCamera;
  24195. }
  24196. var cameraViewport = camera.viewport;
  24197. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24198. // Moving coordinates to local viewport world
  24199. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24200. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24201. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24202. return this;
  24203. };
  24204. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24205. var result = BABYLON.Ray.Zero();
  24206. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24207. return result;
  24208. };
  24209. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24210. if (!BABYLON.PickingInfo) {
  24211. return this;
  24212. }
  24213. var engine = this._engine;
  24214. if (!camera) {
  24215. if (!this.activeCamera)
  24216. throw new Error("Active camera not set");
  24217. camera = this.activeCamera;
  24218. }
  24219. var cameraViewport = camera.viewport;
  24220. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24221. var identity = BABYLON.Matrix.Identity();
  24222. // Moving coordinates to local viewport world
  24223. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24224. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24225. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24226. return this;
  24227. };
  24228. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24229. if (!BABYLON.PickingInfo) {
  24230. return null;
  24231. }
  24232. var pickingInfo = null;
  24233. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24234. var mesh = this.meshes[meshIndex];
  24235. if (predicate) {
  24236. if (!predicate(mesh)) {
  24237. continue;
  24238. }
  24239. }
  24240. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24241. continue;
  24242. }
  24243. var world = mesh.getWorldMatrix();
  24244. var ray = rayFunction(world);
  24245. var result = mesh.intersects(ray, fastCheck);
  24246. if (!result || !result.hit)
  24247. continue;
  24248. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24249. continue;
  24250. pickingInfo = result;
  24251. if (fastCheck) {
  24252. break;
  24253. }
  24254. }
  24255. return pickingInfo || new BABYLON.PickingInfo();
  24256. };
  24257. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24258. if (!BABYLON.PickingInfo) {
  24259. return null;
  24260. }
  24261. var pickingInfos = new Array();
  24262. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24263. var mesh = this.meshes[meshIndex];
  24264. if (predicate) {
  24265. if (!predicate(mesh)) {
  24266. continue;
  24267. }
  24268. }
  24269. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24270. continue;
  24271. }
  24272. var world = mesh.getWorldMatrix();
  24273. var ray = rayFunction(world);
  24274. var result = mesh.intersects(ray, false);
  24275. if (!result || !result.hit)
  24276. continue;
  24277. pickingInfos.push(result);
  24278. }
  24279. return pickingInfos;
  24280. };
  24281. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24282. if (!BABYLON.PickingInfo) {
  24283. return null;
  24284. }
  24285. var pickingInfo = null;
  24286. if (!camera) {
  24287. if (!this.activeCamera) {
  24288. return null;
  24289. }
  24290. camera = this.activeCamera;
  24291. }
  24292. if (this.spriteManagers.length > 0) {
  24293. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24294. var spriteManager = this.spriteManagers[spriteIndex];
  24295. if (!spriteManager.isPickable) {
  24296. continue;
  24297. }
  24298. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24299. if (!result || !result.hit)
  24300. continue;
  24301. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24302. continue;
  24303. pickingInfo = result;
  24304. if (fastCheck) {
  24305. break;
  24306. }
  24307. }
  24308. }
  24309. return pickingInfo || new BABYLON.PickingInfo();
  24310. };
  24311. /** Launch a ray to try to pick a mesh in the scene
  24312. * @param x position on screen
  24313. * @param y position on screen
  24314. * @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
  24315. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24316. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24317. */
  24318. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24319. var _this = this;
  24320. if (!BABYLON.PickingInfo) {
  24321. return null;
  24322. }
  24323. return this._internalPick(function (world) {
  24324. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24325. return _this._tempPickingRay;
  24326. }, predicate, fastCheck);
  24327. };
  24328. /** Launch a ray to try to pick a sprite in the scene
  24329. * @param x position on screen
  24330. * @param y position on screen
  24331. * @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
  24332. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24333. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24334. */
  24335. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24336. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24337. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24338. };
  24339. /** Use the given ray to pick a mesh in the scene
  24340. * @param ray The ray to use to pick meshes
  24341. * @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
  24342. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24343. */
  24344. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24345. var _this = this;
  24346. return this._internalPick(function (world) {
  24347. if (!_this._pickWithRayInverseMatrix) {
  24348. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24349. }
  24350. world.invertToRef(_this._pickWithRayInverseMatrix);
  24351. if (!_this._cachedRayForTransform) {
  24352. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24353. }
  24354. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24355. return _this._cachedRayForTransform;
  24356. }, predicate, fastCheck);
  24357. };
  24358. /**
  24359. * Launch a ray to try to pick a mesh in the scene
  24360. * @param x X position on screen
  24361. * @param y Y position on screen
  24362. * @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
  24363. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24364. */
  24365. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24366. var _this = this;
  24367. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24368. };
  24369. /**
  24370. * Launch a ray to try to pick a mesh in the scene
  24371. * @param ray Ray to use
  24372. * @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
  24373. */
  24374. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24375. var _this = this;
  24376. return this._internalMultiPick(function (world) {
  24377. if (!_this._pickWithRayInverseMatrix) {
  24378. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24379. }
  24380. world.invertToRef(_this._pickWithRayInverseMatrix);
  24381. if (!_this._cachedRayForTransform) {
  24382. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24383. }
  24384. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24385. return _this._cachedRayForTransform;
  24386. }, predicate);
  24387. };
  24388. Scene.prototype.setPointerOverMesh = function (mesh) {
  24389. if (this._pointerOverMesh === mesh) {
  24390. return;
  24391. }
  24392. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24393. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24394. }
  24395. this._pointerOverMesh = mesh;
  24396. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24397. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24398. }
  24399. };
  24400. Scene.prototype.getPointerOverMesh = function () {
  24401. return this._pointerOverMesh;
  24402. };
  24403. Scene.prototype.setPointerOverSprite = function (sprite) {
  24404. if (this._pointerOverSprite === sprite) {
  24405. return;
  24406. }
  24407. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24408. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24409. }
  24410. this._pointerOverSprite = sprite;
  24411. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24412. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24413. }
  24414. };
  24415. Scene.prototype.getPointerOverSprite = function () {
  24416. return this._pointerOverSprite;
  24417. };
  24418. // Physics
  24419. Scene.prototype.getPhysicsEngine = function () {
  24420. return this._physicsEngine;
  24421. };
  24422. /**
  24423. * Enables physics to the current scene
  24424. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24425. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24426. * @return {boolean} was the physics engine initialized
  24427. */
  24428. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24429. if (gravity === void 0) { gravity = null; }
  24430. if (this._physicsEngine) {
  24431. return true;
  24432. }
  24433. try {
  24434. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24435. return true;
  24436. }
  24437. catch (e) {
  24438. BABYLON.Tools.Error(e.message);
  24439. return false;
  24440. }
  24441. };
  24442. Scene.prototype.disablePhysicsEngine = function () {
  24443. if (!this._physicsEngine) {
  24444. return;
  24445. }
  24446. this._physicsEngine.dispose();
  24447. this._physicsEngine = null;
  24448. };
  24449. Scene.prototype.isPhysicsEnabled = function () {
  24450. return this._physicsEngine !== undefined;
  24451. };
  24452. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24453. var mesh = compound.parts[0].mesh;
  24454. if (mesh.physicsImpostor) {
  24455. mesh.physicsImpostor.dispose();
  24456. mesh.physicsImpostor = null;
  24457. }
  24458. };
  24459. // Misc.
  24460. Scene.prototype._rebuildGeometries = function () {
  24461. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24462. var geometry = _a[_i];
  24463. geometry._rebuild();
  24464. }
  24465. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24466. var mesh = _c[_b];
  24467. mesh._rebuild();
  24468. }
  24469. if (this.postProcessManager) {
  24470. this.postProcessManager._rebuild();
  24471. }
  24472. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24473. var layer = _e[_d];
  24474. layer._rebuild();
  24475. }
  24476. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24477. var effectLayer = _g[_f];
  24478. effectLayer._rebuild();
  24479. }
  24480. if (this._boundingBoxRenderer) {
  24481. this._boundingBoxRenderer._rebuild();
  24482. }
  24483. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24484. var system = _j[_h];
  24485. system.rebuild();
  24486. }
  24487. if (this._postProcessRenderPipelineManager) {
  24488. this._postProcessRenderPipelineManager._rebuild();
  24489. }
  24490. };
  24491. Scene.prototype._rebuildTextures = function () {
  24492. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24493. var texture = _a[_i];
  24494. texture._rebuild();
  24495. }
  24496. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24497. };
  24498. /**
  24499. * Creates a default light for the scene.
  24500. * @param replace Whether to replace the existing lights in the scene.
  24501. */
  24502. Scene.prototype.createDefaultLight = function (replace) {
  24503. if (replace === void 0) { replace = false; }
  24504. // Dispose existing light in replace mode.
  24505. if (replace) {
  24506. if (this.lights) {
  24507. for (var i = 0; i < this.lights.length; i++) {
  24508. this.lights[i].dispose();
  24509. }
  24510. }
  24511. }
  24512. // Light
  24513. if (this.lights.length === 0) {
  24514. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24515. }
  24516. };
  24517. /**
  24518. * Creates a default camera for the scene.
  24519. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24520. * @param replace Whether to replace the existing active camera in the scene.
  24521. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24522. */
  24523. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24524. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24525. if (replace === void 0) { replace = false; }
  24526. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24527. // Dispose existing camera in replace mode.
  24528. if (replace) {
  24529. if (this.activeCamera) {
  24530. this.activeCamera.dispose();
  24531. this.activeCamera = null;
  24532. }
  24533. }
  24534. // Camera
  24535. if (!this.activeCamera) {
  24536. var worldExtends = this.getWorldExtends();
  24537. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24538. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24539. var camera;
  24540. var radius = worldSize.length() * 1.5;
  24541. // empty scene scenario!
  24542. if (!isFinite(radius)) {
  24543. radius = 1;
  24544. worldCenter.copyFromFloats(0, 0, 0);
  24545. }
  24546. if (createArcRotateCamera) {
  24547. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24548. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24549. arcRotateCamera.wheelPrecision = 100 / radius;
  24550. camera = arcRotateCamera;
  24551. }
  24552. else {
  24553. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24554. freeCamera.setTarget(worldCenter);
  24555. camera = freeCamera;
  24556. }
  24557. camera.minZ = radius * 0.01;
  24558. camera.maxZ = radius * 1000;
  24559. camera.speed = radius * 0.2;
  24560. this.activeCamera = camera;
  24561. var canvas = this.getEngine().getRenderingCanvas();
  24562. if (attachCameraControls && canvas) {
  24563. camera.attachControl(canvas);
  24564. }
  24565. }
  24566. };
  24567. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24568. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24569. if (replace === void 0) { replace = false; }
  24570. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24571. this.createDefaultLight(replace);
  24572. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24573. };
  24574. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24575. if (pbr === void 0) { pbr = false; }
  24576. if (scale === void 0) { scale = 1000; }
  24577. if (blur === void 0) { blur = 0; }
  24578. if (environmentTexture) {
  24579. this.environmentTexture = environmentTexture;
  24580. }
  24581. if (!this.environmentTexture) {
  24582. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24583. return null;
  24584. }
  24585. // Skybox
  24586. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24587. if (pbr) {
  24588. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24589. hdrSkyboxMaterial.backFaceCulling = false;
  24590. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24591. if (hdrSkyboxMaterial.reflectionTexture) {
  24592. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24593. }
  24594. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24595. hdrSkyboxMaterial.disableLighting = true;
  24596. hdrSkyboxMaterial.twoSidedLighting = true;
  24597. hdrSkybox.infiniteDistance = true;
  24598. hdrSkybox.material = hdrSkyboxMaterial;
  24599. }
  24600. else {
  24601. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24602. skyboxMaterial.backFaceCulling = false;
  24603. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24604. if (skyboxMaterial.reflectionTexture) {
  24605. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24606. }
  24607. skyboxMaterial.disableLighting = true;
  24608. hdrSkybox.infiniteDistance = true;
  24609. hdrSkybox.material = skyboxMaterial;
  24610. }
  24611. return hdrSkybox;
  24612. };
  24613. Scene.prototype.createDefaultEnvironment = function (options) {
  24614. if (BABYLON.EnvironmentHelper) {
  24615. return new BABYLON.EnvironmentHelper(options, this);
  24616. }
  24617. return null;
  24618. };
  24619. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24620. if (webVROptions === void 0) { webVROptions = {}; }
  24621. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24622. };
  24623. // Tags
  24624. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24625. if (tagsQuery === undefined) {
  24626. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24627. return list;
  24628. }
  24629. var listByTags = [];
  24630. forEach = forEach || (function (item) { return; });
  24631. for (var i in list) {
  24632. var item = list[i];
  24633. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24634. listByTags.push(item);
  24635. forEach(item);
  24636. }
  24637. }
  24638. return listByTags;
  24639. };
  24640. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24641. return this._getByTags(this.meshes, tagsQuery, forEach);
  24642. };
  24643. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24644. return this._getByTags(this.cameras, tagsQuery, forEach);
  24645. };
  24646. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24647. return this._getByTags(this.lights, tagsQuery, forEach);
  24648. };
  24649. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24650. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24651. };
  24652. /**
  24653. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24654. * This allowed control for front to back rendering or reversly depending of the special needs.
  24655. *
  24656. * @param renderingGroupId The rendering group id corresponding to its index
  24657. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24658. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24659. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24660. */
  24661. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24662. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24663. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24664. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24665. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24666. };
  24667. /**
  24668. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24669. *
  24670. * @param renderingGroupId The rendering group id corresponding to its index
  24671. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24672. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24673. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24674. */
  24675. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24676. if (depth === void 0) { depth = true; }
  24677. if (stencil === void 0) { stencil = true; }
  24678. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24679. };
  24680. /**
  24681. * Will flag all materials as dirty to trigger new shader compilation
  24682. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24683. */
  24684. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24685. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24686. var material = _a[_i];
  24687. if (predicate && !predicate(material)) {
  24688. continue;
  24689. }
  24690. material.markAsDirty(flag);
  24691. }
  24692. };
  24693. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24694. var _this = this;
  24695. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24696. this._activeRequests.push(request);
  24697. request.onCompleteObservable.add(function (request) {
  24698. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24699. });
  24700. return request;
  24701. };
  24702. /** @ignore */
  24703. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24704. var _this = this;
  24705. return new Promise(function (resolve, reject) {
  24706. _this._loadFile(url, function (data) {
  24707. resolve(data);
  24708. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24709. reject(exception);
  24710. });
  24711. });
  24712. };
  24713. // Statics
  24714. Scene._FOGMODE_NONE = 0;
  24715. Scene._FOGMODE_EXP = 1;
  24716. Scene._FOGMODE_EXP2 = 2;
  24717. Scene._FOGMODE_LINEAR = 3;
  24718. Scene._uniqueIdCounter = 0;
  24719. Scene.MinDeltaTime = 1.0;
  24720. Scene.MaxDeltaTime = 1000.0;
  24721. /** The distance in pixel that you have to move to prevent some events */
  24722. Scene.DragMovementThreshold = 10; // in pixels
  24723. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24724. Scene.LongPressDelay = 500; // in milliseconds
  24725. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24726. Scene.DoubleClickDelay = 300; // in milliseconds
  24727. /** If you need to check double click without raising a single click at first click, enable this flag */
  24728. Scene.ExclusiveDoubleClickMode = false;
  24729. return Scene;
  24730. }());
  24731. BABYLON.Scene = Scene;
  24732. })(BABYLON || (BABYLON = {}));
  24733. //# sourceMappingURL=babylon.scene.js.map
  24734. var BABYLON;
  24735. (function (BABYLON) {
  24736. /**
  24737. * Set of assets to keep when moving a scene into an asset container.
  24738. */
  24739. var KeepAssets = /** @class */ (function () {
  24740. function KeepAssets() {
  24741. /**
  24742. * Cameras to keep.
  24743. */
  24744. this.cameras = new Array();
  24745. /**
  24746. * Lights to keep.
  24747. */
  24748. this.lights = new Array();
  24749. /**
  24750. * Meshes to keep.
  24751. */
  24752. this.meshes = new Array();
  24753. /**
  24754. * Skeletons to keep.
  24755. */
  24756. this.skeletons = new Array();
  24757. /**
  24758. * ParticleSystems to keep.
  24759. */
  24760. this.particleSystems = new Array();
  24761. /**
  24762. * Animations to keep.
  24763. */
  24764. this.animations = new Array();
  24765. /**
  24766. * MultiMaterials to keep.
  24767. */
  24768. this.multiMaterials = new Array();
  24769. /**
  24770. * Materials to keep.
  24771. */
  24772. this.materials = new Array();
  24773. /**
  24774. * MorphTargetManagers to keep.
  24775. */
  24776. this.morphTargetManagers = new Array();
  24777. /**
  24778. * Geometries to keep.
  24779. */
  24780. this.geometries = new Array();
  24781. /**
  24782. * TransformNodes to keep.
  24783. */
  24784. this.transformNodes = new Array();
  24785. /**
  24786. * LensFlareSystems to keep.
  24787. */
  24788. this.lensFlareSystems = new Array();
  24789. /**
  24790. * ShadowGenerators to keep.
  24791. */
  24792. this.shadowGenerators = new Array();
  24793. /**
  24794. * ActionManagers to keep.
  24795. */
  24796. this.actionManagers = new Array();
  24797. /**
  24798. * Sounds to keep.
  24799. */
  24800. this.sounds = new Array();
  24801. }
  24802. return KeepAssets;
  24803. }());
  24804. BABYLON.KeepAssets = KeepAssets;
  24805. /**
  24806. * Container with a set of assets that can be added or removed from a scene.
  24807. */
  24808. var AssetContainer = /** @class */ (function () {
  24809. /**
  24810. * Instantiates an AssetContainer.
  24811. * @param scene The scene the AssetContainer belongs to.
  24812. */
  24813. function AssetContainer(scene) {
  24814. // Objects
  24815. /**
  24816. * Cameras populated in the container.
  24817. */
  24818. this.cameras = new Array();
  24819. /**
  24820. * Lights populated in the container.
  24821. */
  24822. this.lights = new Array();
  24823. /**
  24824. * Meshes populated in the container.
  24825. */
  24826. this.meshes = new Array();
  24827. /**
  24828. * Skeletons populated in the container.
  24829. */
  24830. this.skeletons = new Array();
  24831. /**
  24832. * ParticleSystems populated in the container.
  24833. */
  24834. this.particleSystems = new Array();
  24835. /**
  24836. * Animations populated in the container.
  24837. */
  24838. this.animations = new Array();
  24839. /**
  24840. * MultiMaterials populated in the container.
  24841. */
  24842. this.multiMaterials = new Array();
  24843. /**
  24844. * Materials populated in the container.
  24845. */
  24846. this.materials = new Array();
  24847. /**
  24848. * MorphTargetManagers populated in the container.
  24849. */
  24850. this.morphTargetManagers = new Array();
  24851. /**
  24852. * Geometries populated in the container.
  24853. */
  24854. this.geometries = new Array();
  24855. /**
  24856. * TransformNodes populated in the container.
  24857. */
  24858. this.transformNodes = new Array();
  24859. /**
  24860. * LensFlareSystems populated in the container.
  24861. */
  24862. this.lensFlareSystems = new Array();
  24863. /**
  24864. * ShadowGenerators populated in the container.
  24865. */
  24866. this.shadowGenerators = new Array();
  24867. /**
  24868. * ActionManagers populated in the container.
  24869. */
  24870. this.actionManagers = new Array();
  24871. /**
  24872. * Sounds populated in the container.
  24873. */
  24874. this.sounds = new Array();
  24875. this.scene = scene;
  24876. }
  24877. /**
  24878. * Adds all the assets from the container to the scene.
  24879. */
  24880. AssetContainer.prototype.addAllToScene = function () {
  24881. var _this = this;
  24882. this.cameras.forEach(function (o) {
  24883. _this.scene.addCamera(o);
  24884. });
  24885. this.lights.forEach(function (o) {
  24886. _this.scene.addLight(o);
  24887. });
  24888. this.meshes.forEach(function (o) {
  24889. _this.scene.addMesh(o);
  24890. });
  24891. this.skeletons.forEach(function (o) {
  24892. _this.scene.addSkeleton(o);
  24893. });
  24894. this.particleSystems.forEach(function (o) {
  24895. _this.scene.addParticleSystem(o);
  24896. });
  24897. this.animations.forEach(function (o) {
  24898. _this.scene.addAnimation(o);
  24899. });
  24900. this.multiMaterials.forEach(function (o) {
  24901. _this.scene.addMultiMaterial(o);
  24902. });
  24903. this.materials.forEach(function (o) {
  24904. _this.scene.addMaterial(o);
  24905. });
  24906. this.morphTargetManagers.forEach(function (o) {
  24907. _this.scene.addMorphTargetManager(o);
  24908. });
  24909. this.geometries.forEach(function (o) {
  24910. _this.scene.addGeometry(o);
  24911. });
  24912. this.transformNodes.forEach(function (o) {
  24913. _this.scene.addTransformNode(o);
  24914. });
  24915. this.lensFlareSystems.forEach(function (o) {
  24916. _this.scene.addLensFlareSystem(o);
  24917. });
  24918. this.actionManagers.forEach(function (o) {
  24919. _this.scene.addActionManager(o);
  24920. });
  24921. this.sounds.forEach(function (o) {
  24922. o.play();
  24923. o.autoplay = true;
  24924. _this.scene.mainSoundTrack.AddSound(o);
  24925. });
  24926. };
  24927. /**
  24928. * Removes all the assets in the container from the scene
  24929. */
  24930. AssetContainer.prototype.removeAllFromScene = function () {
  24931. var _this = this;
  24932. this.cameras.forEach(function (o) {
  24933. _this.scene.removeCamera(o);
  24934. });
  24935. this.lights.forEach(function (o) {
  24936. _this.scene.removeLight(o);
  24937. });
  24938. this.meshes.forEach(function (o) {
  24939. _this.scene.removeMesh(o);
  24940. });
  24941. this.skeletons.forEach(function (o) {
  24942. _this.scene.removeSkeleton(o);
  24943. });
  24944. this.particleSystems.forEach(function (o) {
  24945. _this.scene.removeParticleSystem(o);
  24946. });
  24947. this.animations.forEach(function (o) {
  24948. _this.scene.removeAnimation(o);
  24949. });
  24950. this.multiMaterials.forEach(function (o) {
  24951. _this.scene.removeMultiMaterial(o);
  24952. });
  24953. this.materials.forEach(function (o) {
  24954. _this.scene.removeMaterial(o);
  24955. });
  24956. this.morphTargetManagers.forEach(function (o) {
  24957. _this.scene.removeMorphTargetManager(o);
  24958. });
  24959. this.geometries.forEach(function (o) {
  24960. _this.scene.removeGeometry(o);
  24961. });
  24962. this.transformNodes.forEach(function (o) {
  24963. _this.scene.removeTransformNode(o);
  24964. });
  24965. this.lensFlareSystems.forEach(function (o) {
  24966. _this.scene.removeLensFlareSystem(o);
  24967. });
  24968. this.actionManagers.forEach(function (o) {
  24969. _this.scene.removeActionManager(o);
  24970. });
  24971. this.sounds.forEach(function (o) {
  24972. o.stop();
  24973. o.autoplay = false;
  24974. _this.scene.mainSoundTrack.RemoveSound(o);
  24975. });
  24976. };
  24977. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24978. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24979. var asset = sourceAssets_1[_i];
  24980. var move = true;
  24981. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24982. var keepAsset = keepAssets_1[_a];
  24983. if (asset === keepAsset) {
  24984. move = false;
  24985. break;
  24986. }
  24987. }
  24988. if (move) {
  24989. targetAssets.push(asset);
  24990. }
  24991. }
  24992. };
  24993. /**
  24994. * Removes all the assets contained in the scene and adds them to the container.
  24995. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24996. */
  24997. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24998. if (keepAssets === undefined) {
  24999. keepAssets = new KeepAssets();
  25000. }
  25001. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25002. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25003. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25004. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25005. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25006. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25007. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25008. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25009. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25010. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25011. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25012. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25013. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25014. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25015. this.removeAllFromScene();
  25016. };
  25017. return AssetContainer;
  25018. }());
  25019. BABYLON.AssetContainer = AssetContainer;
  25020. })(BABYLON || (BABYLON = {}));
  25021. //# sourceMappingURL=babylon.assetContainer.js.map
  25022. var BABYLON;
  25023. (function (BABYLON) {
  25024. var Buffer = /** @class */ (function () {
  25025. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25026. if (instanced === void 0) { instanced = false; }
  25027. if (engine instanceof BABYLON.Mesh) {
  25028. this._engine = engine.getScene().getEngine();
  25029. }
  25030. else {
  25031. this._engine = engine;
  25032. }
  25033. this._updatable = updatable;
  25034. this._data = data;
  25035. this._strideSize = stride;
  25036. if (!postponeInternalCreation) {
  25037. this.create();
  25038. }
  25039. this._instanced = instanced;
  25040. this._instanceDivisor = instanced ? 1 : 0;
  25041. }
  25042. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25043. // a lot of these parameters are ignored as they are overriden by the buffer
  25044. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25045. };
  25046. // Properties
  25047. Buffer.prototype.isUpdatable = function () {
  25048. return this._updatable;
  25049. };
  25050. Buffer.prototype.getData = function () {
  25051. return this._data;
  25052. };
  25053. Buffer.prototype.getBuffer = function () {
  25054. return this._buffer;
  25055. };
  25056. Buffer.prototype.getStrideSize = function () {
  25057. return this._strideSize;
  25058. };
  25059. Buffer.prototype.getIsInstanced = function () {
  25060. return this._instanced;
  25061. };
  25062. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25063. get: function () {
  25064. return this._instanceDivisor;
  25065. },
  25066. set: function (value) {
  25067. this._instanceDivisor = value;
  25068. if (value == 0) {
  25069. this._instanced = false;
  25070. }
  25071. else {
  25072. this._instanced = true;
  25073. }
  25074. },
  25075. enumerable: true,
  25076. configurable: true
  25077. });
  25078. // Methods
  25079. Buffer.prototype.create = function (data) {
  25080. if (data === void 0) { data = null; }
  25081. if (!data && this._buffer) {
  25082. return; // nothing to do
  25083. }
  25084. data = data || this._data;
  25085. if (!data) {
  25086. return;
  25087. }
  25088. if (!this._buffer) {
  25089. if (this._updatable) {
  25090. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25091. this._data = data;
  25092. }
  25093. else {
  25094. this._buffer = this._engine.createVertexBuffer(data);
  25095. }
  25096. }
  25097. else if (this._updatable) {
  25098. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25099. this._data = data;
  25100. }
  25101. };
  25102. Buffer.prototype._rebuild = function () {
  25103. this._buffer = null;
  25104. this.create(this._data);
  25105. };
  25106. Buffer.prototype.update = function (data) {
  25107. this.create(data);
  25108. };
  25109. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25110. if (!this._buffer) {
  25111. return;
  25112. }
  25113. if (this._updatable) {
  25114. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25115. this._data = null;
  25116. }
  25117. };
  25118. Buffer.prototype.dispose = function () {
  25119. if (!this._buffer) {
  25120. return;
  25121. }
  25122. if (this._engine._releaseBuffer(this._buffer)) {
  25123. this._buffer = null;
  25124. }
  25125. };
  25126. return Buffer;
  25127. }());
  25128. BABYLON.Buffer = Buffer;
  25129. })(BABYLON || (BABYLON = {}));
  25130. //# sourceMappingURL=babylon.buffer.js.map
  25131. var BABYLON;
  25132. (function (BABYLON) {
  25133. var VertexBuffer = /** @class */ (function () {
  25134. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25135. if (!stride) {
  25136. stride = VertexBuffer.DeduceStride(kind);
  25137. }
  25138. if (data instanceof BABYLON.Buffer) {
  25139. if (!stride) {
  25140. stride = data.getStrideSize();
  25141. }
  25142. this._buffer = data;
  25143. this._ownsBuffer = false;
  25144. }
  25145. else {
  25146. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25147. this._ownsBuffer = true;
  25148. }
  25149. this._stride = stride;
  25150. this._offset = offset ? offset : 0;
  25151. this._size = size ? size : stride;
  25152. this._kind = kind;
  25153. }
  25154. VertexBuffer.prototype._rebuild = function () {
  25155. if (!this._buffer) {
  25156. return;
  25157. }
  25158. this._buffer._rebuild();
  25159. };
  25160. /**
  25161. * Returns the kind of the VertexBuffer (string).
  25162. */
  25163. VertexBuffer.prototype.getKind = function () {
  25164. return this._kind;
  25165. };
  25166. // Properties
  25167. /**
  25168. * Boolean : is the VertexBuffer updatable ?
  25169. */
  25170. VertexBuffer.prototype.isUpdatable = function () {
  25171. return this._buffer.isUpdatable();
  25172. };
  25173. /**
  25174. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25175. */
  25176. VertexBuffer.prototype.getData = function () {
  25177. return this._buffer.getData();
  25178. };
  25179. /**
  25180. * Returns the WebGLBuffer associated to the VertexBuffer.
  25181. */
  25182. VertexBuffer.prototype.getBuffer = function () {
  25183. return this._buffer.getBuffer();
  25184. };
  25185. /**
  25186. * Returns the stride of the VertexBuffer (integer).
  25187. */
  25188. VertexBuffer.prototype.getStrideSize = function () {
  25189. return this._stride;
  25190. };
  25191. /**
  25192. * Returns the offset (integer).
  25193. */
  25194. VertexBuffer.prototype.getOffset = function () {
  25195. return this._offset;
  25196. };
  25197. /**
  25198. * Returns the VertexBuffer total size (integer).
  25199. */
  25200. VertexBuffer.prototype.getSize = function () {
  25201. return this._size;
  25202. };
  25203. /**
  25204. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25205. */
  25206. VertexBuffer.prototype.getIsInstanced = function () {
  25207. return this._buffer.getIsInstanced();
  25208. };
  25209. /**
  25210. * Returns the instancing divisor, zero for non-instanced (integer).
  25211. */
  25212. VertexBuffer.prototype.getInstanceDivisor = function () {
  25213. return this._buffer.instanceDivisor;
  25214. };
  25215. // Methods
  25216. /**
  25217. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25218. * Returns the created WebGLBuffer.
  25219. */
  25220. VertexBuffer.prototype.create = function (data) {
  25221. return this._buffer.create(data);
  25222. };
  25223. /**
  25224. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25225. * This function will create a new buffer if the current one is not updatable
  25226. * Returns the updated WebGLBuffer.
  25227. */
  25228. VertexBuffer.prototype.update = function (data) {
  25229. return this._buffer.update(data);
  25230. };
  25231. /**
  25232. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25233. * Returns the directly updated WebGLBuffer.
  25234. */
  25235. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25236. return this._buffer.updateDirectly(data, offset);
  25237. };
  25238. /**
  25239. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25240. */
  25241. VertexBuffer.prototype.dispose = function () {
  25242. if (this._ownsBuffer) {
  25243. this._buffer.dispose();
  25244. }
  25245. };
  25246. Object.defineProperty(VertexBuffer, "PositionKind", {
  25247. get: function () {
  25248. return VertexBuffer._PositionKind;
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. Object.defineProperty(VertexBuffer, "NormalKind", {
  25254. get: function () {
  25255. return VertexBuffer._NormalKind;
  25256. },
  25257. enumerable: true,
  25258. configurable: true
  25259. });
  25260. Object.defineProperty(VertexBuffer, "TangentKind", {
  25261. get: function () {
  25262. return VertexBuffer._TangentKind;
  25263. },
  25264. enumerable: true,
  25265. configurable: true
  25266. });
  25267. Object.defineProperty(VertexBuffer, "UVKind", {
  25268. get: function () {
  25269. return VertexBuffer._UVKind;
  25270. },
  25271. enumerable: true,
  25272. configurable: true
  25273. });
  25274. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25275. get: function () {
  25276. return VertexBuffer._UV2Kind;
  25277. },
  25278. enumerable: true,
  25279. configurable: true
  25280. });
  25281. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25282. get: function () {
  25283. return VertexBuffer._UV3Kind;
  25284. },
  25285. enumerable: true,
  25286. configurable: true
  25287. });
  25288. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25289. get: function () {
  25290. return VertexBuffer._UV4Kind;
  25291. },
  25292. enumerable: true,
  25293. configurable: true
  25294. });
  25295. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25296. get: function () {
  25297. return VertexBuffer._UV5Kind;
  25298. },
  25299. enumerable: true,
  25300. configurable: true
  25301. });
  25302. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25303. get: function () {
  25304. return VertexBuffer._UV6Kind;
  25305. },
  25306. enumerable: true,
  25307. configurable: true
  25308. });
  25309. Object.defineProperty(VertexBuffer, "ColorKind", {
  25310. get: function () {
  25311. return VertexBuffer._ColorKind;
  25312. },
  25313. enumerable: true,
  25314. configurable: true
  25315. });
  25316. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25317. get: function () {
  25318. return VertexBuffer._MatricesIndicesKind;
  25319. },
  25320. enumerable: true,
  25321. configurable: true
  25322. });
  25323. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25324. get: function () {
  25325. return VertexBuffer._MatricesWeightsKind;
  25326. },
  25327. enumerable: true,
  25328. configurable: true
  25329. });
  25330. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25331. get: function () {
  25332. return VertexBuffer._MatricesIndicesExtraKind;
  25333. },
  25334. enumerable: true,
  25335. configurable: true
  25336. });
  25337. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25338. get: function () {
  25339. return VertexBuffer._MatricesWeightsExtraKind;
  25340. },
  25341. enumerable: true,
  25342. configurable: true
  25343. });
  25344. /**
  25345. * Deduces the stride given a kind.
  25346. * @param kind The kind string to deduce
  25347. * @returns The deduced stride
  25348. */
  25349. VertexBuffer.DeduceStride = function (kind) {
  25350. switch (kind) {
  25351. case VertexBuffer.PositionKind:
  25352. return 3;
  25353. case VertexBuffer.NormalKind:
  25354. return 3;
  25355. case VertexBuffer.UVKind:
  25356. case VertexBuffer.UV2Kind:
  25357. case VertexBuffer.UV3Kind:
  25358. case VertexBuffer.UV4Kind:
  25359. case VertexBuffer.UV5Kind:
  25360. case VertexBuffer.UV6Kind:
  25361. return 2;
  25362. case VertexBuffer.TangentKind:
  25363. case VertexBuffer.ColorKind:
  25364. return 4;
  25365. case VertexBuffer.MatricesIndicesKind:
  25366. case VertexBuffer.MatricesIndicesExtraKind:
  25367. return 4;
  25368. case VertexBuffer.MatricesWeightsKind:
  25369. case VertexBuffer.MatricesWeightsExtraKind:
  25370. return 4;
  25371. default:
  25372. throw new Error("Invalid kind '" + kind + "'");
  25373. }
  25374. };
  25375. // Enums
  25376. VertexBuffer._PositionKind = "position";
  25377. VertexBuffer._NormalKind = "normal";
  25378. VertexBuffer._TangentKind = "tangent";
  25379. VertexBuffer._UVKind = "uv";
  25380. VertexBuffer._UV2Kind = "uv2";
  25381. VertexBuffer._UV3Kind = "uv3";
  25382. VertexBuffer._UV4Kind = "uv4";
  25383. VertexBuffer._UV5Kind = "uv5";
  25384. VertexBuffer._UV6Kind = "uv6";
  25385. VertexBuffer._ColorKind = "color";
  25386. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25387. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25388. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25389. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25390. return VertexBuffer;
  25391. }());
  25392. BABYLON.VertexBuffer = VertexBuffer;
  25393. })(BABYLON || (BABYLON = {}));
  25394. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25395. var BABYLON;
  25396. (function (BABYLON) {
  25397. /**
  25398. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25399. */
  25400. var DummyInternalTextureTracker = /** @class */ (function () {
  25401. function DummyInternalTextureTracker() {
  25402. /**
  25403. * Gets or set the previous tracker in the list
  25404. */
  25405. this.previous = null;
  25406. /**
  25407. * Gets or set the next tracker in the list
  25408. */
  25409. this.next = null;
  25410. }
  25411. return DummyInternalTextureTracker;
  25412. }());
  25413. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25414. })(BABYLON || (BABYLON = {}));
  25415. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25416. var BABYLON;
  25417. (function (BABYLON) {
  25418. /**
  25419. * Class used to store data associated with WebGL texture data for the engine
  25420. * This class should not be used directly
  25421. */
  25422. var InternalTexture = /** @class */ (function () {
  25423. /**
  25424. * Creates a new InternalTexture
  25425. * @param engine defines the engine to use
  25426. * @param dataSource defines the type of data that will be used
  25427. */
  25428. function InternalTexture(engine, dataSource) {
  25429. /**
  25430. * Observable called when the texture is loaded
  25431. */
  25432. this.onLoadedObservable = new BABYLON.Observable();
  25433. /**
  25434. * Gets or set the previous tracker in the list
  25435. */
  25436. this.previous = null;
  25437. /**
  25438. * Gets or set the next tracker in the list
  25439. */
  25440. this.next = null;
  25441. // Private
  25442. /** @ignore */
  25443. this._initialSlot = -1;
  25444. /** @ignore */
  25445. this._designatedSlot = -1;
  25446. /** @ignore */
  25447. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25448. /** @ignore */
  25449. this._references = 1;
  25450. this._engine = engine;
  25451. this._dataSource = dataSource;
  25452. this._webGLTexture = engine._createTexture();
  25453. }
  25454. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25455. /**
  25456. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25457. */
  25458. get: function () {
  25459. return this._dataSource;
  25460. },
  25461. enumerable: true,
  25462. configurable: true
  25463. });
  25464. /**
  25465. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25466. */
  25467. InternalTexture.prototype.incrementReferences = function () {
  25468. this._references++;
  25469. };
  25470. /**
  25471. * Change the size of the texture (not the size of the content)
  25472. * @param width defines the new width
  25473. * @param height defines the new height
  25474. * @param depth defines the new depth (1 by default)
  25475. */
  25476. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25477. if (depth === void 0) { depth = 1; }
  25478. this.width = width;
  25479. this.height = height;
  25480. this.depth = depth;
  25481. this.baseWidth = width;
  25482. this.baseHeight = height;
  25483. this.baseDepth = depth;
  25484. this._size = width * height * depth;
  25485. };
  25486. /** @ignore */
  25487. InternalTexture.prototype._rebuild = function () {
  25488. var _this = this;
  25489. var proxy;
  25490. this.isReady = false;
  25491. this._cachedCoordinatesMode = null;
  25492. this._cachedWrapU = null;
  25493. this._cachedWrapV = null;
  25494. this._cachedAnisotropicFilteringLevel = null;
  25495. switch (this._dataSource) {
  25496. case InternalTexture.DATASOURCE_TEMP:
  25497. return;
  25498. case InternalTexture.DATASOURCE_URL:
  25499. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25500. _this.isReady = true;
  25501. }, null, this._buffer, undefined, this.format);
  25502. proxy._swapAndDie(this);
  25503. return;
  25504. case InternalTexture.DATASOURCE_RAW:
  25505. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25506. proxy._swapAndDie(this);
  25507. this.isReady = true;
  25508. return;
  25509. case InternalTexture.DATASOURCE_RAW3D:
  25510. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25511. proxy._swapAndDie(this);
  25512. this.isReady = true;
  25513. return;
  25514. case InternalTexture.DATASOURCE_DYNAMIC:
  25515. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25516. proxy._swapAndDie(this);
  25517. // The engine will make sure to update content so no need to flag it as isReady = true
  25518. return;
  25519. case InternalTexture.DATASOURCE_RENDERTARGET:
  25520. var options = new BABYLON.RenderTargetCreationOptions();
  25521. options.generateDepthBuffer = this._generateDepthBuffer;
  25522. options.generateMipMaps = this.generateMipMaps;
  25523. options.generateStencilBuffer = this._generateStencilBuffer;
  25524. options.samplingMode = this.samplingMode;
  25525. options.type = this.type;
  25526. if (this.isCube) {
  25527. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25528. }
  25529. else {
  25530. var size = {
  25531. width: this.width,
  25532. height: this.height
  25533. };
  25534. proxy = this._engine.createRenderTargetTexture(size, options);
  25535. }
  25536. proxy._swapAndDie(this);
  25537. this.isReady = true;
  25538. return;
  25539. case InternalTexture.DATASOURCE_CUBE:
  25540. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25541. _this.isReady = true;
  25542. }, null, this.format, this._extension);
  25543. proxy._swapAndDie(this);
  25544. return;
  25545. case InternalTexture.DATASOURCE_CUBERAW:
  25546. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25547. proxy._swapAndDie(this);
  25548. this.isReady = true;
  25549. return;
  25550. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25551. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25552. if (proxy) {
  25553. proxy._swapAndDie(_this);
  25554. }
  25555. _this.isReady = true;
  25556. }, null, this.format, this._extension);
  25557. return;
  25558. }
  25559. };
  25560. InternalTexture.prototype._swapAndDie = function (target) {
  25561. target._webGLTexture = this._webGLTexture;
  25562. if (this._framebuffer) {
  25563. target._framebuffer = this._framebuffer;
  25564. }
  25565. if (this._depthStencilBuffer) {
  25566. target._depthStencilBuffer = this._depthStencilBuffer;
  25567. }
  25568. if (this._lodTextureHigh) {
  25569. if (target._lodTextureHigh) {
  25570. target._lodTextureHigh.dispose();
  25571. }
  25572. target._lodTextureHigh = this._lodTextureHigh;
  25573. }
  25574. if (this._lodTextureMid) {
  25575. if (target._lodTextureMid) {
  25576. target._lodTextureMid.dispose();
  25577. }
  25578. target._lodTextureMid = this._lodTextureMid;
  25579. }
  25580. if (this._lodTextureLow) {
  25581. if (target._lodTextureLow) {
  25582. target._lodTextureLow.dispose();
  25583. }
  25584. target._lodTextureLow = this._lodTextureLow;
  25585. }
  25586. var cache = this._engine.getLoadedTexturesCache();
  25587. var index = cache.indexOf(this);
  25588. if (index !== -1) {
  25589. cache.splice(index, 1);
  25590. }
  25591. };
  25592. /**
  25593. * Dispose the current allocated resources
  25594. */
  25595. InternalTexture.prototype.dispose = function () {
  25596. if (!this._webGLTexture) {
  25597. return;
  25598. }
  25599. this._references--;
  25600. if (this._references === 0) {
  25601. this._engine._releaseTexture(this);
  25602. this._webGLTexture = null;
  25603. this.previous = null;
  25604. this.next = null;
  25605. }
  25606. };
  25607. /**
  25608. * The source of the texture data is unknown
  25609. */
  25610. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25611. /**
  25612. * Texture data comes from an URL
  25613. */
  25614. InternalTexture.DATASOURCE_URL = 1;
  25615. /**
  25616. * Texture data is only used for temporary storage
  25617. */
  25618. InternalTexture.DATASOURCE_TEMP = 2;
  25619. /**
  25620. * Texture data comes from raw data (ArrayBuffer)
  25621. */
  25622. InternalTexture.DATASOURCE_RAW = 3;
  25623. /**
  25624. * Texture content is dynamic (video or dynamic texture)
  25625. */
  25626. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25627. /**
  25628. * Texture content is generated by rendering to it
  25629. */
  25630. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25631. /**
  25632. * Texture content is part of a multi render target process
  25633. */
  25634. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25635. /**
  25636. * Texture data comes from a cube data file
  25637. */
  25638. InternalTexture.DATASOURCE_CUBE = 7;
  25639. /**
  25640. * Texture data comes from a raw cube data
  25641. */
  25642. InternalTexture.DATASOURCE_CUBERAW = 8;
  25643. /**
  25644. * Texture data come from a prefiltered cube data file
  25645. */
  25646. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25647. /**
  25648. * Texture content is raw 3D data
  25649. */
  25650. InternalTexture.DATASOURCE_RAW3D = 10;
  25651. return InternalTexture;
  25652. }());
  25653. BABYLON.InternalTexture = InternalTexture;
  25654. })(BABYLON || (BABYLON = {}));
  25655. //# sourceMappingURL=babylon.internalTexture.js.map
  25656. var BABYLON;
  25657. (function (BABYLON) {
  25658. var BaseTexture = /** @class */ (function () {
  25659. function BaseTexture(scene) {
  25660. this._hasAlpha = false;
  25661. this.getAlphaFromRGB = false;
  25662. this.level = 1;
  25663. this.coordinatesIndex = 0;
  25664. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25665. /*
  25666. * How a texture is mapped.
  25667. *
  25668. * | Value | Type | Description |
  25669. * | ----- | ----------------------------------- | ----------- |
  25670. * | 0 | EXPLICIT_MODE | |
  25671. * | 1 | SPHERICAL_MODE | |
  25672. * | 2 | PLANAR_MODE | |
  25673. * | 3 | CUBIC_MODE | |
  25674. * | 4 | PROJECTION_MODE | |
  25675. * | 5 | SKYBOX_MODE | |
  25676. * | 6 | INVCUBIC_MODE | |
  25677. * | 7 | EQUIRECTANGULAR_MODE | |
  25678. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25679. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25680. */
  25681. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25682. /*
  25683. * | Value | Type | Description |
  25684. * | ----- | ------------------ | ----------- |
  25685. * | 0 | CLAMP_ADDRESSMODE | |
  25686. * | 1 | WRAP_ADDRESSMODE | |
  25687. * | 2 | MIRROR_ADDRESSMODE | |
  25688. */
  25689. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25690. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25691. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25692. this.isCube = false;
  25693. this.is3D = false;
  25694. this.gammaSpace = true;
  25695. this.invertZ = false;
  25696. this.lodLevelInAlpha = false;
  25697. this.lodGenerationOffset = 0.0;
  25698. this.lodGenerationScale = 0.8;
  25699. this.isRenderTarget = false;
  25700. this.animations = new Array();
  25701. /**
  25702. * An event triggered when the texture is disposed.
  25703. * @type {BABYLON.Observable}
  25704. */
  25705. this.onDisposeObservable = new BABYLON.Observable();
  25706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25707. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25708. if (this._scene) {
  25709. this._scene.textures.push(this);
  25710. }
  25711. this._uid = null;
  25712. }
  25713. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25714. get: function () {
  25715. return this._hasAlpha;
  25716. },
  25717. set: function (value) {
  25718. if (this._hasAlpha === value) {
  25719. return;
  25720. }
  25721. this._hasAlpha = value;
  25722. if (this._scene) {
  25723. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25724. }
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25730. get: function () {
  25731. return this._coordinatesMode;
  25732. },
  25733. set: function (value) {
  25734. if (this._coordinatesMode === value) {
  25735. return;
  25736. }
  25737. this._coordinatesMode = value;
  25738. if (this._scene) {
  25739. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25740. }
  25741. },
  25742. enumerable: true,
  25743. configurable: true
  25744. });
  25745. Object.defineProperty(BaseTexture.prototype, "uid", {
  25746. get: function () {
  25747. if (!this._uid) {
  25748. this._uid = BABYLON.Tools.RandomId();
  25749. }
  25750. return this._uid;
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. BaseTexture.prototype.toString = function () {
  25756. return this.name;
  25757. };
  25758. BaseTexture.prototype.getClassName = function () {
  25759. return "BaseTexture";
  25760. };
  25761. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25762. set: function (callback) {
  25763. if (this._onDisposeObserver) {
  25764. this.onDisposeObservable.remove(this._onDisposeObserver);
  25765. }
  25766. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25767. },
  25768. enumerable: true,
  25769. configurable: true
  25770. });
  25771. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25772. get: function () {
  25773. return true;
  25774. },
  25775. enumerable: true,
  25776. configurable: true
  25777. });
  25778. BaseTexture.prototype.getScene = function () {
  25779. return this._scene;
  25780. };
  25781. BaseTexture.prototype.getTextureMatrix = function () {
  25782. return BABYLON.Matrix.IdentityReadOnly;
  25783. };
  25784. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25785. return BABYLON.Matrix.IdentityReadOnly;
  25786. };
  25787. BaseTexture.prototype.getInternalTexture = function () {
  25788. return this._texture;
  25789. };
  25790. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25791. return !this.isBlocking || this.isReady();
  25792. };
  25793. BaseTexture.prototype.isReady = function () {
  25794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25795. this.delayLoad();
  25796. return false;
  25797. }
  25798. if (this._texture) {
  25799. return this._texture.isReady;
  25800. }
  25801. return false;
  25802. };
  25803. BaseTexture.prototype.getSize = function () {
  25804. if (this._texture && this._texture.width) {
  25805. return new BABYLON.Size(this._texture.width, this._texture.height);
  25806. }
  25807. if (this._texture && this._texture._size) {
  25808. return new BABYLON.Size(this._texture._size, this._texture._size);
  25809. }
  25810. return BABYLON.Size.Zero();
  25811. };
  25812. BaseTexture.prototype.getBaseSize = function () {
  25813. if (!this.isReady() || !this._texture)
  25814. return BABYLON.Size.Zero();
  25815. if (this._texture._size) {
  25816. return new BABYLON.Size(this._texture._size, this._texture._size);
  25817. }
  25818. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25819. };
  25820. BaseTexture.prototype.scale = function (ratio) {
  25821. };
  25822. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25823. get: function () {
  25824. return false;
  25825. },
  25826. enumerable: true,
  25827. configurable: true
  25828. });
  25829. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25830. if (!this._scene) {
  25831. return null;
  25832. }
  25833. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25834. for (var index = 0; index < texturesCache.length; index++) {
  25835. var texturesCacheEntry = texturesCache[index];
  25836. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25837. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25838. texturesCacheEntry.incrementReferences();
  25839. return texturesCacheEntry;
  25840. }
  25841. }
  25842. }
  25843. return null;
  25844. };
  25845. BaseTexture.prototype._rebuild = function () {
  25846. };
  25847. BaseTexture.prototype.delayLoad = function () {
  25848. };
  25849. BaseTexture.prototype.clone = function () {
  25850. return null;
  25851. };
  25852. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25853. get: function () {
  25854. if (!this._texture) {
  25855. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25856. }
  25857. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25858. },
  25859. enumerable: true,
  25860. configurable: true
  25861. });
  25862. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25863. get: function () {
  25864. if (!this._texture) {
  25865. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25866. }
  25867. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. BaseTexture.prototype.readPixels = function (faceIndex) {
  25873. if (faceIndex === void 0) { faceIndex = 0; }
  25874. if (!this._texture) {
  25875. return null;
  25876. }
  25877. var size = this.getSize();
  25878. var scene = this.getScene();
  25879. if (!scene) {
  25880. return null;
  25881. }
  25882. var engine = scene.getEngine();
  25883. if (this._texture.isCube) {
  25884. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25885. }
  25886. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25887. };
  25888. BaseTexture.prototype.releaseInternalTexture = function () {
  25889. if (this._texture) {
  25890. this._texture.dispose();
  25891. this._texture = null;
  25892. }
  25893. };
  25894. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25895. get: function () {
  25896. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25897. return null;
  25898. }
  25899. if (!this._texture._sphericalPolynomial) {
  25900. this._texture._sphericalPolynomial =
  25901. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25902. }
  25903. return this._texture._sphericalPolynomial;
  25904. },
  25905. set: function (value) {
  25906. if (this._texture) {
  25907. this._texture._sphericalPolynomial = value;
  25908. }
  25909. },
  25910. enumerable: true,
  25911. configurable: true
  25912. });
  25913. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25914. get: function () {
  25915. if (this._texture) {
  25916. return this._texture._lodTextureHigh;
  25917. }
  25918. return null;
  25919. },
  25920. enumerable: true,
  25921. configurable: true
  25922. });
  25923. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25924. get: function () {
  25925. if (this._texture) {
  25926. return this._texture._lodTextureMid;
  25927. }
  25928. return null;
  25929. },
  25930. enumerable: true,
  25931. configurable: true
  25932. });
  25933. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25934. get: function () {
  25935. if (this._texture) {
  25936. return this._texture._lodTextureLow;
  25937. }
  25938. return null;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. BaseTexture.prototype.dispose = function () {
  25944. if (!this._scene) {
  25945. return;
  25946. }
  25947. // Animations
  25948. this._scene.stopAnimation(this);
  25949. // Remove from scene
  25950. this._scene._removePendingData(this);
  25951. var index = this._scene.textures.indexOf(this);
  25952. if (index >= 0) {
  25953. this._scene.textures.splice(index, 1);
  25954. }
  25955. if (this._texture === undefined) {
  25956. return;
  25957. }
  25958. // Release
  25959. this.releaseInternalTexture();
  25960. // Callback
  25961. this.onDisposeObservable.notifyObservers(this);
  25962. this.onDisposeObservable.clear();
  25963. };
  25964. BaseTexture.prototype.serialize = function () {
  25965. if (!this.name) {
  25966. return null;
  25967. }
  25968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25969. // Animations
  25970. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25971. return serializationObject;
  25972. };
  25973. BaseTexture.WhenAllReady = function (textures, callback) {
  25974. var numRemaining = textures.length;
  25975. if (numRemaining === 0) {
  25976. callback();
  25977. return;
  25978. }
  25979. var _loop_1 = function () {
  25980. texture = textures[i];
  25981. if (texture.isReady()) {
  25982. if (--numRemaining === 0) {
  25983. callback();
  25984. }
  25985. }
  25986. else {
  25987. onLoadObservable = texture.onLoadObservable;
  25988. var onLoadCallback_1 = function () {
  25989. onLoadObservable.removeCallback(onLoadCallback_1);
  25990. if (--numRemaining === 0) {
  25991. callback();
  25992. }
  25993. };
  25994. onLoadObservable.add(onLoadCallback_1);
  25995. }
  25996. };
  25997. var texture, onLoadObservable;
  25998. for (var i = 0; i < textures.length; i++) {
  25999. _loop_1();
  26000. }
  26001. };
  26002. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26003. __decorate([
  26004. BABYLON.serialize()
  26005. ], BaseTexture.prototype, "name", void 0);
  26006. __decorate([
  26007. BABYLON.serialize("hasAlpha")
  26008. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26009. __decorate([
  26010. BABYLON.serialize()
  26011. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26012. __decorate([
  26013. BABYLON.serialize()
  26014. ], BaseTexture.prototype, "level", void 0);
  26015. __decorate([
  26016. BABYLON.serialize()
  26017. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26018. __decorate([
  26019. BABYLON.serialize("coordinatesMode")
  26020. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26021. __decorate([
  26022. BABYLON.serialize()
  26023. ], BaseTexture.prototype, "wrapU", void 0);
  26024. __decorate([
  26025. BABYLON.serialize()
  26026. ], BaseTexture.prototype, "wrapV", void 0);
  26027. __decorate([
  26028. BABYLON.serialize()
  26029. ], BaseTexture.prototype, "wrapR", void 0);
  26030. __decorate([
  26031. BABYLON.serialize()
  26032. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26033. __decorate([
  26034. BABYLON.serialize()
  26035. ], BaseTexture.prototype, "isCube", void 0);
  26036. __decorate([
  26037. BABYLON.serialize()
  26038. ], BaseTexture.prototype, "is3D", void 0);
  26039. __decorate([
  26040. BABYLON.serialize()
  26041. ], BaseTexture.prototype, "gammaSpace", void 0);
  26042. __decorate([
  26043. BABYLON.serialize()
  26044. ], BaseTexture.prototype, "invertZ", void 0);
  26045. __decorate([
  26046. BABYLON.serialize()
  26047. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26048. __decorate([
  26049. BABYLON.serialize()
  26050. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26051. __decorate([
  26052. BABYLON.serialize()
  26053. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26054. __decorate([
  26055. BABYLON.serialize()
  26056. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26057. return BaseTexture;
  26058. }());
  26059. BABYLON.BaseTexture = BaseTexture;
  26060. })(BABYLON || (BABYLON = {}));
  26061. //# sourceMappingURL=babylon.baseTexture.js.map
  26062. var BABYLON;
  26063. (function (BABYLON) {
  26064. var Texture = /** @class */ (function (_super) {
  26065. __extends(Texture, _super);
  26066. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26067. if (noMipmap === void 0) { noMipmap = false; }
  26068. if (invertY === void 0) { invertY = true; }
  26069. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26070. if (onLoad === void 0) { onLoad = null; }
  26071. if (onError === void 0) { onError = null; }
  26072. if (buffer === void 0) { buffer = null; }
  26073. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26074. var _this = _super.call(this, scene) || this;
  26075. _this.uOffset = 0;
  26076. _this.vOffset = 0;
  26077. _this.uScale = 1.0;
  26078. _this.vScale = 1.0;
  26079. _this.uAng = 0;
  26080. _this.vAng = 0;
  26081. _this.wAng = 0;
  26082. _this._isBlocking = true;
  26083. _this.name = url || "";
  26084. _this.url = url;
  26085. _this._noMipmap = noMipmap;
  26086. _this._invertY = invertY;
  26087. _this._samplingMode = samplingMode;
  26088. _this._buffer = buffer;
  26089. _this._deleteBuffer = deleteBuffer;
  26090. if (format) {
  26091. _this._format = format;
  26092. }
  26093. scene = _this.getScene();
  26094. if (!scene) {
  26095. return _this;
  26096. }
  26097. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26098. var load = function () {
  26099. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26100. _this.onLoadObservable.notifyObservers(_this);
  26101. }
  26102. if (onLoad) {
  26103. onLoad();
  26104. }
  26105. if (!_this.isBlocking && scene) {
  26106. scene.resetCachedMaterial();
  26107. }
  26108. };
  26109. if (!_this.url) {
  26110. _this._delayedOnLoad = load;
  26111. _this._delayedOnError = onError;
  26112. return _this;
  26113. }
  26114. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26115. if (!_this._texture) {
  26116. if (!scene.useDelayedTextureLoading) {
  26117. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26118. if (deleteBuffer) {
  26119. delete _this._buffer;
  26120. }
  26121. }
  26122. else {
  26123. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26124. _this._delayedOnLoad = load;
  26125. _this._delayedOnError = onError;
  26126. }
  26127. }
  26128. else {
  26129. if (_this._texture.isReady) {
  26130. BABYLON.Tools.SetImmediate(function () { return load(); });
  26131. }
  26132. else {
  26133. _this._texture.onLoadedObservable.add(load);
  26134. }
  26135. }
  26136. return _this;
  26137. }
  26138. Object.defineProperty(Texture.prototype, "noMipmap", {
  26139. get: function () {
  26140. return this._noMipmap;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. Object.defineProperty(Texture.prototype, "isBlocking", {
  26146. get: function () {
  26147. return this._isBlocking;
  26148. },
  26149. set: function (value) {
  26150. this._isBlocking = value;
  26151. },
  26152. enumerable: true,
  26153. configurable: true
  26154. });
  26155. Object.defineProperty(Texture.prototype, "samplingMode", {
  26156. get: function () {
  26157. return this._samplingMode;
  26158. },
  26159. enumerable: true,
  26160. configurable: true
  26161. });
  26162. Texture.prototype.updateURL = function (url) {
  26163. this.url = url;
  26164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26165. this.delayLoad();
  26166. };
  26167. Texture.prototype.delayLoad = function () {
  26168. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26169. return;
  26170. }
  26171. var scene = this.getScene();
  26172. if (!scene) {
  26173. return;
  26174. }
  26175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26176. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26177. if (!this._texture) {
  26178. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26179. if (this._deleteBuffer) {
  26180. delete this._buffer;
  26181. }
  26182. }
  26183. else {
  26184. if (this._delayedOnLoad) {
  26185. if (this._texture.isReady) {
  26186. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26187. }
  26188. else {
  26189. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26190. }
  26191. }
  26192. }
  26193. this._delayedOnLoad = null;
  26194. this._delayedOnError = null;
  26195. };
  26196. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26197. if (!this._texture) {
  26198. return;
  26199. }
  26200. var scene = this.getScene();
  26201. if (!scene) {
  26202. return;
  26203. }
  26204. this._samplingMode = samplingMode;
  26205. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26206. };
  26207. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26208. x *= this.uScale;
  26209. y *= this.vScale;
  26210. x -= 0.5 * this.uScale;
  26211. y -= 0.5 * this.vScale;
  26212. z -= 0.5;
  26213. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26214. t.x += 0.5 * this.uScale + this.uOffset;
  26215. t.y += 0.5 * this.vScale + this.vOffset;
  26216. t.z += 0.5;
  26217. };
  26218. Texture.prototype.getTextureMatrix = function () {
  26219. var _this = this;
  26220. if (this.uOffset === this._cachedUOffset &&
  26221. this.vOffset === this._cachedVOffset &&
  26222. this.uScale === this._cachedUScale &&
  26223. this.vScale === this._cachedVScale &&
  26224. this.uAng === this._cachedUAng &&
  26225. this.vAng === this._cachedVAng &&
  26226. this.wAng === this._cachedWAng) {
  26227. return this._cachedTextureMatrix;
  26228. }
  26229. this._cachedUOffset = this.uOffset;
  26230. this._cachedVOffset = this.vOffset;
  26231. this._cachedUScale = this.uScale;
  26232. this._cachedVScale = this.vScale;
  26233. this._cachedUAng = this.uAng;
  26234. this._cachedVAng = this.vAng;
  26235. this._cachedWAng = this.wAng;
  26236. if (!this._cachedTextureMatrix) {
  26237. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26238. this._rowGenerationMatrix = new BABYLON.Matrix();
  26239. this._t0 = BABYLON.Vector3.Zero();
  26240. this._t1 = BABYLON.Vector3.Zero();
  26241. this._t2 = BABYLON.Vector3.Zero();
  26242. }
  26243. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26244. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26245. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26246. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26247. this._t1.subtractInPlace(this._t0);
  26248. this._t2.subtractInPlace(this._t0);
  26249. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26250. this._cachedTextureMatrix.m[0] = this._t1.x;
  26251. this._cachedTextureMatrix.m[1] = this._t1.y;
  26252. this._cachedTextureMatrix.m[2] = this._t1.z;
  26253. this._cachedTextureMatrix.m[4] = this._t2.x;
  26254. this._cachedTextureMatrix.m[5] = this._t2.y;
  26255. this._cachedTextureMatrix.m[6] = this._t2.z;
  26256. this._cachedTextureMatrix.m[8] = this._t0.x;
  26257. this._cachedTextureMatrix.m[9] = this._t0.y;
  26258. this._cachedTextureMatrix.m[10] = this._t0.z;
  26259. var scene = this.getScene();
  26260. if (!scene) {
  26261. return this._cachedTextureMatrix;
  26262. }
  26263. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26264. return mat.hasTexture(_this);
  26265. });
  26266. return this._cachedTextureMatrix;
  26267. };
  26268. Texture.prototype.getReflectionTextureMatrix = function () {
  26269. var _this = this;
  26270. var scene = this.getScene();
  26271. if (!scene) {
  26272. return this._cachedTextureMatrix;
  26273. }
  26274. if (this.uOffset === this._cachedUOffset &&
  26275. this.vOffset === this._cachedVOffset &&
  26276. this.uScale === this._cachedUScale &&
  26277. this.vScale === this._cachedVScale &&
  26278. this.coordinatesMode === this._cachedCoordinatesMode) {
  26279. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26280. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26281. return this._cachedTextureMatrix;
  26282. }
  26283. }
  26284. else {
  26285. return this._cachedTextureMatrix;
  26286. }
  26287. }
  26288. if (!this._cachedTextureMatrix) {
  26289. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26290. }
  26291. if (!this._projectionModeMatrix) {
  26292. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26293. }
  26294. this._cachedUOffset = this.uOffset;
  26295. this._cachedVOffset = this.vOffset;
  26296. this._cachedUScale = this.uScale;
  26297. this._cachedVScale = this.vScale;
  26298. this._cachedCoordinatesMode = this.coordinatesMode;
  26299. switch (this.coordinatesMode) {
  26300. case Texture.PLANAR_MODE:
  26301. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26302. this._cachedTextureMatrix[0] = this.uScale;
  26303. this._cachedTextureMatrix[5] = this.vScale;
  26304. this._cachedTextureMatrix[12] = this.uOffset;
  26305. this._cachedTextureMatrix[13] = this.vOffset;
  26306. break;
  26307. case Texture.PROJECTION_MODE:
  26308. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26309. this._projectionModeMatrix.m[0] = 0.5;
  26310. this._projectionModeMatrix.m[5] = -0.5;
  26311. this._projectionModeMatrix.m[10] = 0.0;
  26312. this._projectionModeMatrix.m[12] = 0.5;
  26313. this._projectionModeMatrix.m[13] = 0.5;
  26314. this._projectionModeMatrix.m[14] = 1.0;
  26315. this._projectionModeMatrix.m[15] = 1.0;
  26316. var projectionMatrix = scene.getProjectionMatrix();
  26317. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26318. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26319. break;
  26320. default:
  26321. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26322. break;
  26323. }
  26324. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26325. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26326. });
  26327. return this._cachedTextureMatrix;
  26328. };
  26329. Texture.prototype.clone = function () {
  26330. var _this = this;
  26331. return BABYLON.SerializationHelper.Clone(function () {
  26332. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26333. }, this);
  26334. };
  26335. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26336. get: function () {
  26337. if (!this._onLoadObservable) {
  26338. this._onLoadObservable = new BABYLON.Observable();
  26339. }
  26340. return this._onLoadObservable;
  26341. },
  26342. enumerable: true,
  26343. configurable: true
  26344. });
  26345. Texture.prototype.serialize = function () {
  26346. var serializationObject = _super.prototype.serialize.call(this);
  26347. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26348. serializationObject.base64String = this._buffer;
  26349. serializationObject.name = serializationObject.name.replace("data:", "");
  26350. }
  26351. return serializationObject;
  26352. };
  26353. Texture.prototype.getClassName = function () {
  26354. return "Texture";
  26355. };
  26356. Texture.prototype.dispose = function () {
  26357. _super.prototype.dispose.call(this);
  26358. if (this.onLoadObservable) {
  26359. this.onLoadObservable.clear();
  26360. this._onLoadObservable = null;
  26361. }
  26362. this._delayedOnLoad = null;
  26363. this._delayedOnError = null;
  26364. };
  26365. // Statics
  26366. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26367. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26368. if (onLoad === void 0) { onLoad = null; }
  26369. if (onError === void 0) { onError = null; }
  26370. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26371. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26372. };
  26373. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26374. if (parsedTexture.customType) {
  26375. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26376. // Update Sampling Mode
  26377. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26378. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26379. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26380. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26381. }
  26382. }
  26383. return parsedCustomTexture;
  26384. }
  26385. if (parsedTexture.isCube) {
  26386. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26387. }
  26388. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26389. return null;
  26390. }
  26391. var texture = BABYLON.SerializationHelper.Parse(function () {
  26392. var generateMipMaps = true;
  26393. if (parsedTexture.noMipmap) {
  26394. generateMipMaps = false;
  26395. }
  26396. if (parsedTexture.mirrorPlane) {
  26397. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26398. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26399. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26400. return mirrorTexture;
  26401. }
  26402. else if (parsedTexture.isRenderTarget) {
  26403. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26404. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26405. return renderTargetTexture;
  26406. }
  26407. else {
  26408. var texture;
  26409. if (parsedTexture.base64String) {
  26410. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26411. }
  26412. else {
  26413. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26414. }
  26415. return texture;
  26416. }
  26417. }, parsedTexture, scene);
  26418. // Update Sampling Mode
  26419. if (parsedTexture.samplingMode) {
  26420. var sampling = parsedTexture.samplingMode;
  26421. if (texture._samplingMode !== sampling) {
  26422. texture.updateSamplingMode(sampling);
  26423. }
  26424. }
  26425. // Animations
  26426. if (parsedTexture.animations) {
  26427. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26428. var parsedAnimation = parsedTexture.animations[animationIndex];
  26429. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26430. }
  26431. }
  26432. return texture;
  26433. };
  26434. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26435. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26436. if (noMipmap === void 0) { noMipmap = false; }
  26437. if (invertY === void 0) { invertY = true; }
  26438. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26439. if (onLoad === void 0) { onLoad = null; }
  26440. if (onError === void 0) { onError = null; }
  26441. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26442. if (name.substr(0, 5) !== "data:") {
  26443. name = "data:" + name;
  26444. }
  26445. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26446. };
  26447. // Constants
  26448. Texture.NEAREST_SAMPLINGMODE = 1;
  26449. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26450. Texture.BILINEAR_SAMPLINGMODE = 2;
  26451. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26452. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26453. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26454. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26455. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26456. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26457. Texture.NEAREST_LINEAR = 7;
  26458. Texture.NEAREST_NEAREST = 8;
  26459. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26460. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26461. Texture.LINEAR_LINEAR = 11;
  26462. Texture.LINEAR_NEAREST = 12;
  26463. Texture.EXPLICIT_MODE = 0;
  26464. Texture.SPHERICAL_MODE = 1;
  26465. Texture.PLANAR_MODE = 2;
  26466. Texture.CUBIC_MODE = 3;
  26467. Texture.PROJECTION_MODE = 4;
  26468. Texture.SKYBOX_MODE = 5;
  26469. Texture.INVCUBIC_MODE = 6;
  26470. Texture.EQUIRECTANGULAR_MODE = 7;
  26471. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26472. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26473. Texture.CLAMP_ADDRESSMODE = 0;
  26474. Texture.WRAP_ADDRESSMODE = 1;
  26475. Texture.MIRROR_ADDRESSMODE = 2;
  26476. __decorate([
  26477. BABYLON.serialize()
  26478. ], Texture.prototype, "url", void 0);
  26479. __decorate([
  26480. BABYLON.serialize()
  26481. ], Texture.prototype, "uOffset", void 0);
  26482. __decorate([
  26483. BABYLON.serialize()
  26484. ], Texture.prototype, "vOffset", void 0);
  26485. __decorate([
  26486. BABYLON.serialize()
  26487. ], Texture.prototype, "uScale", void 0);
  26488. __decorate([
  26489. BABYLON.serialize()
  26490. ], Texture.prototype, "vScale", void 0);
  26491. __decorate([
  26492. BABYLON.serialize()
  26493. ], Texture.prototype, "uAng", void 0);
  26494. __decorate([
  26495. BABYLON.serialize()
  26496. ], Texture.prototype, "vAng", void 0);
  26497. __decorate([
  26498. BABYLON.serialize()
  26499. ], Texture.prototype, "wAng", void 0);
  26500. __decorate([
  26501. BABYLON.serialize()
  26502. ], Texture.prototype, "isBlocking", null);
  26503. return Texture;
  26504. }(BABYLON.BaseTexture));
  26505. BABYLON.Texture = Texture;
  26506. })(BABYLON || (BABYLON = {}));
  26507. //# sourceMappingURL=babylon.texture.js.map
  26508. var BABYLON;
  26509. (function (BABYLON) {
  26510. var _InstancesBatch = /** @class */ (function () {
  26511. function _InstancesBatch() {
  26512. this.mustReturn = false;
  26513. this.visibleInstances = new Array();
  26514. this.renderSelf = new Array();
  26515. }
  26516. return _InstancesBatch;
  26517. }());
  26518. BABYLON._InstancesBatch = _InstancesBatch;
  26519. var Mesh = /** @class */ (function (_super) {
  26520. __extends(Mesh, _super);
  26521. /**
  26522. * @constructor
  26523. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26524. * @param {Scene} scene The scene to add this mesh to.
  26525. * @param {Node} parent The parent of this mesh, if it has one
  26526. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26527. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26528. * When false, achieved by calling a clone(), also passing False.
  26529. * This will make creation of children, recursive.
  26530. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26531. */
  26532. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26533. if (scene === void 0) { scene = null; }
  26534. if (parent === void 0) { parent = null; }
  26535. if (source === void 0) { source = null; }
  26536. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26537. var _this = _super.call(this, name, scene) || this;
  26538. // Events
  26539. /**
  26540. * An event triggered before rendering the mesh
  26541. * @type {BABYLON.Observable}
  26542. */
  26543. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26544. /**
  26545. * An event triggered after rendering the mesh
  26546. * @type {BABYLON.Observable}
  26547. */
  26548. _this.onAfterRenderObservable = new BABYLON.Observable();
  26549. /**
  26550. * An event triggered before drawing the mesh
  26551. * @type {BABYLON.Observable}
  26552. */
  26553. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26554. // Members
  26555. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26556. _this.instances = new Array();
  26557. _this._LODLevels = new Array();
  26558. _this._visibleInstances = {};
  26559. _this._renderIdForInstances = new Array();
  26560. _this._batchCache = new _InstancesBatch();
  26561. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26562. // Use by builder only to know what orientation were the mesh build in.
  26563. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26564. _this.overrideMaterialSideOrientation = null;
  26565. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26566. // Will be used to save a source mesh reference, If any
  26567. _this._source = null;
  26568. scene = _this.getScene();
  26569. if (source) {
  26570. // Source mesh
  26571. _this._source = source;
  26572. // Geometry
  26573. if (source._geometry) {
  26574. source._geometry.applyToMesh(_this);
  26575. }
  26576. // Deep copy
  26577. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26578. // Metadata
  26579. if (source.metadata && source.metadata.clone) {
  26580. _this.metadata = source.metadata.clone();
  26581. }
  26582. else {
  26583. _this.metadata = source.metadata;
  26584. }
  26585. // Tags
  26586. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26587. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26588. }
  26589. // Parent
  26590. _this.parent = source.parent;
  26591. // Pivot
  26592. _this.setPivotMatrix(source.getPivotMatrix());
  26593. _this.id = name + "." + source.id;
  26594. // Material
  26595. _this.material = source.material;
  26596. var index;
  26597. if (!doNotCloneChildren) {
  26598. // Children
  26599. var directDescendants = source.getDescendants(true);
  26600. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26601. var child = directDescendants[index_1];
  26602. if (child.clone) {
  26603. child.clone(name + "." + child.name, _this);
  26604. }
  26605. }
  26606. }
  26607. // Physics clone
  26608. var physicsEngine = _this.getScene().getPhysicsEngine();
  26609. if (clonePhysicsImpostor && physicsEngine) {
  26610. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26611. if (impostor) {
  26612. _this.physicsImpostor = impostor.clone(_this);
  26613. }
  26614. }
  26615. // Particles
  26616. for (index = 0; index < scene.particleSystems.length; index++) {
  26617. var system = scene.particleSystems[index];
  26618. if (system.emitter === source) {
  26619. system.clone(system.name, _this);
  26620. }
  26621. }
  26622. _this.computeWorldMatrix(true);
  26623. }
  26624. // Parent
  26625. if (parent !== null) {
  26626. _this.parent = parent;
  26627. }
  26628. return _this;
  26629. }
  26630. Object.defineProperty(Mesh, "FRONTSIDE", {
  26631. /**
  26632. * Mesh side orientation : usually the external or front surface
  26633. */
  26634. get: function () {
  26635. return Mesh._FRONTSIDE;
  26636. },
  26637. enumerable: true,
  26638. configurable: true
  26639. });
  26640. Object.defineProperty(Mesh, "BACKSIDE", {
  26641. /**
  26642. * Mesh side orientation : usually the internal or back surface
  26643. */
  26644. get: function () {
  26645. return Mesh._BACKSIDE;
  26646. },
  26647. enumerable: true,
  26648. configurable: true
  26649. });
  26650. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26651. /**
  26652. * Mesh side orientation : both internal and external or front and back surfaces
  26653. */
  26654. get: function () {
  26655. return Mesh._DOUBLESIDE;
  26656. },
  26657. enumerable: true,
  26658. configurable: true
  26659. });
  26660. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26661. /**
  26662. * Mesh side orientation : by default, `FRONTSIDE`
  26663. */
  26664. get: function () {
  26665. return Mesh._DEFAULTSIDE;
  26666. },
  26667. enumerable: true,
  26668. configurable: true
  26669. });
  26670. Object.defineProperty(Mesh, "NO_CAP", {
  26671. /**
  26672. * Mesh cap setting : no cap
  26673. */
  26674. get: function () {
  26675. return Mesh._NO_CAP;
  26676. },
  26677. enumerable: true,
  26678. configurable: true
  26679. });
  26680. Object.defineProperty(Mesh, "CAP_START", {
  26681. /**
  26682. * Mesh cap setting : one cap at the beginning of the mesh
  26683. */
  26684. get: function () {
  26685. return Mesh._CAP_START;
  26686. },
  26687. enumerable: true,
  26688. configurable: true
  26689. });
  26690. Object.defineProperty(Mesh, "CAP_END", {
  26691. /**
  26692. * Mesh cap setting : one cap at the end of the mesh
  26693. */
  26694. get: function () {
  26695. return Mesh._CAP_END;
  26696. },
  26697. enumerable: true,
  26698. configurable: true
  26699. });
  26700. Object.defineProperty(Mesh, "CAP_ALL", {
  26701. /**
  26702. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26703. */
  26704. get: function () {
  26705. return Mesh._CAP_ALL;
  26706. },
  26707. enumerable: true,
  26708. configurable: true
  26709. });
  26710. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26711. set: function (callback) {
  26712. if (this._onBeforeDrawObserver) {
  26713. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26714. }
  26715. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26716. },
  26717. enumerable: true,
  26718. configurable: true
  26719. });
  26720. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26721. get: function () {
  26722. return this._morphTargetManager;
  26723. },
  26724. set: function (value) {
  26725. if (this._morphTargetManager === value) {
  26726. return;
  26727. }
  26728. this._morphTargetManager = value;
  26729. this._syncGeometryWithMorphTargetManager();
  26730. },
  26731. enumerable: true,
  26732. configurable: true
  26733. });
  26734. Object.defineProperty(Mesh.prototype, "source", {
  26735. get: function () {
  26736. return this._source;
  26737. },
  26738. enumerable: true,
  26739. configurable: true
  26740. });
  26741. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26742. get: function () {
  26743. return this._unIndexed;
  26744. },
  26745. set: function (value) {
  26746. if (this._unIndexed !== value) {
  26747. this._unIndexed = value;
  26748. this._markSubMeshesAsAttributesDirty();
  26749. }
  26750. },
  26751. enumerable: true,
  26752. configurable: true
  26753. });
  26754. // Methods
  26755. /**
  26756. * Returns the string "Mesh".
  26757. */
  26758. Mesh.prototype.getClassName = function () {
  26759. return "Mesh";
  26760. };
  26761. /**
  26762. * Returns a string.
  26763. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26764. */
  26765. Mesh.prototype.toString = function (fullDetails) {
  26766. var ret = _super.prototype.toString.call(this, fullDetails);
  26767. ret += ", n vertices: " + this.getTotalVertices();
  26768. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26769. if (this.animations) {
  26770. for (var i = 0; i < this.animations.length; i++) {
  26771. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26772. }
  26773. }
  26774. if (fullDetails) {
  26775. if (this._geometry) {
  26776. var ib = this.getIndices();
  26777. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26778. if (vb && ib) {
  26779. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26780. }
  26781. }
  26782. else {
  26783. ret += ", flat shading: UNKNOWN";
  26784. }
  26785. }
  26786. return ret;
  26787. };
  26788. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26789. /**
  26790. * True if the mesh has some Levels Of Details (LOD).
  26791. * Returns a boolean.
  26792. */
  26793. get: function () {
  26794. return this._LODLevels.length > 0;
  26795. },
  26796. enumerable: true,
  26797. configurable: true
  26798. });
  26799. /**
  26800. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26801. * @returns an array of {BABYLON.MeshLODLevel}
  26802. */
  26803. Mesh.prototype.getLODLevels = function () {
  26804. return this._LODLevels;
  26805. };
  26806. Mesh.prototype._sortLODLevels = function () {
  26807. this._LODLevels.sort(function (a, b) {
  26808. if (a.distance < b.distance) {
  26809. return 1;
  26810. }
  26811. if (a.distance > b.distance) {
  26812. return -1;
  26813. }
  26814. return 0;
  26815. });
  26816. };
  26817. /**
  26818. * Add a mesh as LOD level triggered at the given distance.
  26819. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26820. * @param {number} distance The distance from the center of the object to show this level
  26821. * @param {Mesh} mesh The mesh to be added as LOD level
  26822. * @return {Mesh} This mesh (for chaining)
  26823. */
  26824. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26825. if (mesh && mesh._masterMesh) {
  26826. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26827. return this;
  26828. }
  26829. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26830. this._LODLevels.push(level);
  26831. if (mesh) {
  26832. mesh._masterMesh = this;
  26833. }
  26834. this._sortLODLevels();
  26835. return this;
  26836. };
  26837. /**
  26838. * Returns the LOD level mesh at the passed distance or null if not found.
  26839. * It is related to the method `addLODLevel(distance, mesh)`.
  26840. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26841. * Returns an object Mesh or `null`.
  26842. */
  26843. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26844. for (var index = 0; index < this._LODLevels.length; index++) {
  26845. var level = this._LODLevels[index];
  26846. if (level.distance === distance) {
  26847. return level.mesh;
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Remove a mesh from the LOD array
  26854. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26855. * @param {Mesh} mesh The mesh to be removed.
  26856. * @return {Mesh} This mesh (for chaining)
  26857. */
  26858. Mesh.prototype.removeLODLevel = function (mesh) {
  26859. for (var index = 0; index < this._LODLevels.length; index++) {
  26860. if (this._LODLevels[index].mesh === mesh) {
  26861. this._LODLevels.splice(index, 1);
  26862. if (mesh) {
  26863. mesh._masterMesh = null;
  26864. }
  26865. }
  26866. }
  26867. this._sortLODLevels();
  26868. return this;
  26869. };
  26870. /**
  26871. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26872. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26873. */
  26874. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26875. if (!this._LODLevels || this._LODLevels.length === 0) {
  26876. return this;
  26877. }
  26878. var bSphere;
  26879. if (boundingSphere) {
  26880. bSphere = boundingSphere;
  26881. }
  26882. else {
  26883. var boundingInfo = this.getBoundingInfo();
  26884. bSphere = boundingInfo.boundingSphere;
  26885. }
  26886. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26887. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26888. if (this.onLODLevelSelection) {
  26889. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26890. }
  26891. return this;
  26892. }
  26893. for (var index = 0; index < this._LODLevels.length; index++) {
  26894. var level = this._LODLevels[index];
  26895. if (level.distance < distanceToCamera) {
  26896. if (level.mesh) {
  26897. level.mesh._preActivate();
  26898. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26899. }
  26900. if (this.onLODLevelSelection) {
  26901. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26902. }
  26903. return level.mesh;
  26904. }
  26905. }
  26906. if (this.onLODLevelSelection) {
  26907. this.onLODLevelSelection(distanceToCamera, this, this);
  26908. }
  26909. return this;
  26910. };
  26911. Object.defineProperty(Mesh.prototype, "geometry", {
  26912. /**
  26913. * Returns the mesh internal Geometry object.
  26914. */
  26915. get: function () {
  26916. return this._geometry;
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. /**
  26922. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26923. */
  26924. Mesh.prototype.getTotalVertices = function () {
  26925. if (this._geometry === null || this._geometry === undefined) {
  26926. return 0;
  26927. }
  26928. return this._geometry.getTotalVertices();
  26929. };
  26930. /**
  26931. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26932. * 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.
  26933. * You can force the copy with forceCopy === true
  26934. * Returns null if the mesh has no geometry or no vertex buffer.
  26935. * Possible `kind` values :
  26936. * - BABYLON.VertexBuffer.PositionKind
  26937. * - BABYLON.VertexBuffer.UVKind
  26938. * - BABYLON.VertexBuffer.UV2Kind
  26939. * - BABYLON.VertexBuffer.UV3Kind
  26940. * - BABYLON.VertexBuffer.UV4Kind
  26941. * - BABYLON.VertexBuffer.UV5Kind
  26942. * - BABYLON.VertexBuffer.UV6Kind
  26943. * - BABYLON.VertexBuffer.ColorKind
  26944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26948. */
  26949. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26950. if (!this._geometry) {
  26951. return null;
  26952. }
  26953. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26954. };
  26955. /**
  26956. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26957. * Returns `null` if the mesh has no geometry.
  26958. * Possible `kind` values :
  26959. * - BABYLON.VertexBuffer.PositionKind
  26960. * - BABYLON.VertexBuffer.UVKind
  26961. * - BABYLON.VertexBuffer.UV2Kind
  26962. * - BABYLON.VertexBuffer.UV3Kind
  26963. * - BABYLON.VertexBuffer.UV4Kind
  26964. * - BABYLON.VertexBuffer.UV5Kind
  26965. * - BABYLON.VertexBuffer.UV6Kind
  26966. * - BABYLON.VertexBuffer.ColorKind
  26967. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26968. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26969. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26970. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26971. */
  26972. Mesh.prototype.getVertexBuffer = function (kind) {
  26973. if (!this._geometry) {
  26974. return null;
  26975. }
  26976. return this._geometry.getVertexBuffer(kind);
  26977. };
  26978. /**
  26979. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26980. * Possible `kind` values :
  26981. * - BABYLON.VertexBuffer.PositionKind
  26982. * - BABYLON.VertexBuffer.UVKind
  26983. * - BABYLON.VertexBuffer.UV2Kind
  26984. * - BABYLON.VertexBuffer.UV3Kind
  26985. * - BABYLON.VertexBuffer.UV4Kind
  26986. * - BABYLON.VertexBuffer.UV5Kind
  26987. * - BABYLON.VertexBuffer.UV6Kind
  26988. * - BABYLON.VertexBuffer.ColorKind
  26989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26993. */
  26994. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26995. if (!this._geometry) {
  26996. if (this._delayInfo) {
  26997. return this._delayInfo.indexOf(kind) !== -1;
  26998. }
  26999. return false;
  27000. }
  27001. return this._geometry.isVerticesDataPresent(kind);
  27002. };
  27003. /**
  27004. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27005. * Possible `kind` values :
  27006. * - BABYLON.VertexBuffer.PositionKind
  27007. * - BABYLON.VertexBuffer.UVKind
  27008. * - BABYLON.VertexBuffer.UV2Kind
  27009. * - BABYLON.VertexBuffer.UV3Kind
  27010. * - BABYLON.VertexBuffer.UV4Kind
  27011. * - BABYLON.VertexBuffer.UV5Kind
  27012. * - BABYLON.VertexBuffer.UV6Kind
  27013. * - BABYLON.VertexBuffer.ColorKind
  27014. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27015. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27016. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27017. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27018. */
  27019. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27020. if (!this._geometry) {
  27021. if (this._delayInfo) {
  27022. return this._delayInfo.indexOf(kind) !== -1;
  27023. }
  27024. return false;
  27025. }
  27026. return this._geometry.isVertexBufferUpdatable(kind);
  27027. };
  27028. /**
  27029. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27030. * Possible `kind` values :
  27031. * - BABYLON.VertexBuffer.PositionKind
  27032. * - BABYLON.VertexBuffer.UVKind
  27033. * - BABYLON.VertexBuffer.UV2Kind
  27034. * - BABYLON.VertexBuffer.UV3Kind
  27035. * - BABYLON.VertexBuffer.UV4Kind
  27036. * - BABYLON.VertexBuffer.UV5Kind
  27037. * - BABYLON.VertexBuffer.UV6Kind
  27038. * - BABYLON.VertexBuffer.ColorKind
  27039. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27040. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27041. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27042. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27043. */
  27044. Mesh.prototype.getVerticesDataKinds = function () {
  27045. if (!this._geometry) {
  27046. var result = new Array();
  27047. if (this._delayInfo) {
  27048. this._delayInfo.forEach(function (kind, index, array) {
  27049. result.push(kind);
  27050. });
  27051. }
  27052. return result;
  27053. }
  27054. return this._geometry.getVerticesDataKinds();
  27055. };
  27056. /**
  27057. * Returns a positive integer : the total number of indices in this mesh geometry.
  27058. * Returns zero if the mesh has no geometry.
  27059. */
  27060. Mesh.prototype.getTotalIndices = function () {
  27061. if (!this._geometry) {
  27062. return 0;
  27063. }
  27064. return this._geometry.getTotalIndices();
  27065. };
  27066. /**
  27067. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27068. * 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.
  27069. * Returns an empty array if the mesh has no geometry.
  27070. */
  27071. Mesh.prototype.getIndices = function (copyWhenShared) {
  27072. if (!this._geometry) {
  27073. return [];
  27074. }
  27075. return this._geometry.getIndices(copyWhenShared);
  27076. };
  27077. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27078. get: function () {
  27079. return this._masterMesh !== null && this._masterMesh !== undefined;
  27080. },
  27081. enumerable: true,
  27082. configurable: true
  27083. });
  27084. /**
  27085. * Determine if the current mesh is ready to be rendered
  27086. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27087. * @returns true if all associated assets are ready (material, textures, shaders)
  27088. */
  27089. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27090. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27091. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27092. return false;
  27093. }
  27094. if (!_super.prototype.isReady.call(this)) {
  27095. return false;
  27096. }
  27097. if (!this.subMeshes || this.subMeshes.length === 0) {
  27098. return true;
  27099. }
  27100. var engine = this.getEngine();
  27101. var scene = this.getScene();
  27102. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27103. this.computeWorldMatrix();
  27104. var mat = this.material || scene.defaultMaterial;
  27105. if (mat) {
  27106. if (mat.storeEffectOnSubMeshes) {
  27107. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27108. var subMesh = _a[_i];
  27109. var effectiveMaterial = subMesh.getMaterial();
  27110. if (effectiveMaterial) {
  27111. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27112. return false;
  27113. }
  27114. }
  27115. }
  27116. }
  27117. else {
  27118. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27119. return false;
  27120. }
  27121. }
  27122. }
  27123. // Shadows
  27124. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27125. var light = _c[_b];
  27126. var generator = light.getShadowGenerator();
  27127. if (generator) {
  27128. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27129. var subMesh = _e[_d];
  27130. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27131. return false;
  27132. }
  27133. }
  27134. }
  27135. }
  27136. // LOD
  27137. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27138. var lod = _g[_f];
  27139. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27140. return false;
  27141. }
  27142. }
  27143. return true;
  27144. };
  27145. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27146. /**
  27147. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27148. * This property is pertinent only for updatable parametric shapes.
  27149. */
  27150. get: function () {
  27151. return this._areNormalsFrozen;
  27152. },
  27153. enumerable: true,
  27154. configurable: true
  27155. });
  27156. /**
  27157. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27158. * It has no effect at all on other shapes.
  27159. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27160. * Returns the Mesh.
  27161. */
  27162. Mesh.prototype.freezeNormals = function () {
  27163. this._areNormalsFrozen = true;
  27164. return this;
  27165. };
  27166. /**
  27167. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27168. * It has no effect at all on other shapes.
  27169. * It reactivates the mesh normals computation if it was previously frozen.
  27170. * Returns the Mesh.
  27171. */
  27172. Mesh.prototype.unfreezeNormals = function () {
  27173. this._areNormalsFrozen = false;
  27174. return this;
  27175. };
  27176. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27177. /**
  27178. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27179. */
  27180. set: function (count) {
  27181. this._overridenInstanceCount = count;
  27182. },
  27183. enumerable: true,
  27184. configurable: true
  27185. });
  27186. // Methods
  27187. Mesh.prototype._preActivate = function () {
  27188. var sceneRenderId = this.getScene().getRenderId();
  27189. if (this._preActivateId === sceneRenderId) {
  27190. return this;
  27191. }
  27192. this._preActivateId = sceneRenderId;
  27193. this._visibleInstances = null;
  27194. return this;
  27195. };
  27196. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27197. if (this._visibleInstances) {
  27198. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27199. }
  27200. return this;
  27201. };
  27202. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27203. if (!this._visibleInstances) {
  27204. this._visibleInstances = {};
  27205. this._visibleInstances.defaultRenderId = renderId;
  27206. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27207. }
  27208. if (!this._visibleInstances[renderId]) {
  27209. this._visibleInstances[renderId] = new Array();
  27210. }
  27211. this._visibleInstances[renderId].push(instance);
  27212. return this;
  27213. };
  27214. /**
  27215. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27216. * This means the mesh underlying bounding box and sphere are recomputed.
  27217. * Returns the Mesh.
  27218. */
  27219. Mesh.prototype.refreshBoundingInfo = function () {
  27220. return this._refreshBoundingInfo(false);
  27221. };
  27222. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27223. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27224. return this;
  27225. }
  27226. var data = this._getPositionData(applySkeleton);
  27227. if (data) {
  27228. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27229. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27230. }
  27231. if (this.subMeshes) {
  27232. for (var index = 0; index < this.subMeshes.length; index++) {
  27233. this.subMeshes[index].refreshBoundingInfo();
  27234. }
  27235. }
  27236. this._updateBoundingInfo();
  27237. return this;
  27238. };
  27239. Mesh.prototype._getPositionData = function (applySkeleton) {
  27240. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27241. if (data && applySkeleton && this.skeleton) {
  27242. data = BABYLON.Tools.Slice(data);
  27243. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27244. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27245. if (matricesWeightsData && matricesIndicesData) {
  27246. var needExtras = this.numBoneInfluencers > 4;
  27247. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27248. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27249. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27250. var tempVector = BABYLON.Tmp.Vector3[0];
  27251. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27252. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27253. var matWeightIdx = 0;
  27254. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27255. finalMatrix.reset();
  27256. var inf;
  27257. var weight;
  27258. for (inf = 0; inf < 4; inf++) {
  27259. weight = matricesWeightsData[matWeightIdx + inf];
  27260. if (weight <= 0)
  27261. break;
  27262. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27263. finalMatrix.addToSelf(tempMatrix);
  27264. }
  27265. if (needExtras) {
  27266. for (inf = 0; inf < 4; inf++) {
  27267. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27268. if (weight <= 0)
  27269. break;
  27270. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27271. finalMatrix.addToSelf(tempMatrix);
  27272. }
  27273. }
  27274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27275. tempVector.toArray(data, index);
  27276. }
  27277. }
  27278. }
  27279. return data;
  27280. };
  27281. Mesh.prototype._createGlobalSubMesh = function (force) {
  27282. var totalVertices = this.getTotalVertices();
  27283. if (!totalVertices || !this.getIndices()) {
  27284. return null;
  27285. }
  27286. // Check if we need to recreate the submeshes
  27287. if (this.subMeshes && this.subMeshes.length > 0) {
  27288. var ib = this.getIndices();
  27289. if (!ib) {
  27290. return null;
  27291. }
  27292. var totalIndices = ib.length;
  27293. var needToRecreate = false;
  27294. if (force) {
  27295. needToRecreate = true;
  27296. }
  27297. else {
  27298. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27299. var submesh = _a[_i];
  27300. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27301. needToRecreate = true;
  27302. break;
  27303. }
  27304. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27305. needToRecreate = true;
  27306. break;
  27307. }
  27308. }
  27309. }
  27310. if (!needToRecreate) {
  27311. return this.subMeshes[0];
  27312. }
  27313. }
  27314. this.releaseSubMeshes();
  27315. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27316. };
  27317. Mesh.prototype.subdivide = function (count) {
  27318. if (count < 1) {
  27319. return;
  27320. }
  27321. var totalIndices = this.getTotalIndices();
  27322. var subdivisionSize = (totalIndices / count) | 0;
  27323. var offset = 0;
  27324. // Ensure that subdivisionSize is a multiple of 3
  27325. while (subdivisionSize % 3 !== 0) {
  27326. subdivisionSize++;
  27327. }
  27328. this.releaseSubMeshes();
  27329. for (var index = 0; index < count; index++) {
  27330. if (offset >= totalIndices) {
  27331. break;
  27332. }
  27333. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27334. offset += subdivisionSize;
  27335. }
  27336. this.synchronizeInstances();
  27337. };
  27338. /**
  27339. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27340. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27341. * The `data` are either a numeric array either a Float32Array.
  27342. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27343. * 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).
  27344. * Note that a new underlying VertexBuffer object is created each call.
  27345. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27346. *
  27347. * Possible `kind` values :
  27348. * - BABYLON.VertexBuffer.PositionKind
  27349. * - BABYLON.VertexBuffer.UVKind
  27350. * - BABYLON.VertexBuffer.UV2Kind
  27351. * - BABYLON.VertexBuffer.UV3Kind
  27352. * - BABYLON.VertexBuffer.UV4Kind
  27353. * - BABYLON.VertexBuffer.UV5Kind
  27354. * - BABYLON.VertexBuffer.UV6Kind
  27355. * - BABYLON.VertexBuffer.ColorKind
  27356. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27357. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27358. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27359. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27360. *
  27361. * Returns the Mesh.
  27362. */
  27363. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27364. if (updatable === void 0) { updatable = false; }
  27365. if (!this._geometry) {
  27366. var vertexData = new BABYLON.VertexData();
  27367. vertexData.set(data, kind);
  27368. var scene = this.getScene();
  27369. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27370. }
  27371. else {
  27372. this._geometry.setVerticesData(kind, data, updatable, stride);
  27373. }
  27374. return this;
  27375. };
  27376. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27377. if (updatable === void 0) { updatable = true; }
  27378. var vb = this.getVertexBuffer(kind);
  27379. if (!vb || vb.isUpdatable() === updatable) {
  27380. return;
  27381. }
  27382. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27383. };
  27384. /**
  27385. * Sets the mesh VertexBuffer.
  27386. * Returns the Mesh.
  27387. */
  27388. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27389. if (!this._geometry) {
  27390. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27391. }
  27392. this._geometry.setVerticesBuffer(buffer);
  27393. return this;
  27394. };
  27395. /**
  27396. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27397. * If the mesh has no geometry, it is simply returned as it is.
  27398. * The `data` are either a numeric array either a Float32Array.
  27399. * No new underlying VertexBuffer object is created.
  27400. * 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.
  27401. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27402. *
  27403. * Possible `kind` values :
  27404. * - BABYLON.VertexBuffer.PositionKind
  27405. * - BABYLON.VertexBuffer.UVKind
  27406. * - BABYLON.VertexBuffer.UV2Kind
  27407. * - BABYLON.VertexBuffer.UV3Kind
  27408. * - BABYLON.VertexBuffer.UV4Kind
  27409. * - BABYLON.VertexBuffer.UV5Kind
  27410. * - BABYLON.VertexBuffer.UV6Kind
  27411. * - BABYLON.VertexBuffer.ColorKind
  27412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27416. *
  27417. * Returns the Mesh.
  27418. */
  27419. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27420. if (!this._geometry) {
  27421. return this;
  27422. }
  27423. if (!makeItUnique) {
  27424. this._geometry.updateVerticesData(kind, data, updateExtends);
  27425. }
  27426. else {
  27427. this.makeGeometryUnique();
  27428. this.updateVerticesData(kind, data, updateExtends, false);
  27429. }
  27430. return this;
  27431. };
  27432. /**
  27433. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27434. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27435. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27436. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27437. * Returns the Mesh.
  27438. */
  27439. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27440. if (computeNormals === void 0) { computeNormals = true; }
  27441. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27442. if (!positions) {
  27443. return this;
  27444. }
  27445. positionFunction(positions);
  27446. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27447. if (computeNormals) {
  27448. var indices = this.getIndices();
  27449. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27450. if (!normals) {
  27451. return this;
  27452. }
  27453. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27454. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27455. }
  27456. return this;
  27457. };
  27458. /**
  27459. * Creates a un-shared specific occurence of the geometry for the mesh.
  27460. * Returns the Mesh.
  27461. */
  27462. Mesh.prototype.makeGeometryUnique = function () {
  27463. if (!this._geometry) {
  27464. return this;
  27465. }
  27466. var oldGeometry = this._geometry;
  27467. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27468. oldGeometry.releaseForMesh(this, true);
  27469. geometry.applyToMesh(this);
  27470. return this;
  27471. };
  27472. /**
  27473. * Sets the mesh indices.
  27474. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27475. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27476. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27477. * This method creates a new index buffer each call.
  27478. * Returns the Mesh.
  27479. */
  27480. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27481. if (totalVertices === void 0) { totalVertices = null; }
  27482. if (updatable === void 0) { updatable = false; }
  27483. if (!this._geometry) {
  27484. var vertexData = new BABYLON.VertexData();
  27485. vertexData.indices = indices;
  27486. var scene = this.getScene();
  27487. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27488. }
  27489. else {
  27490. this._geometry.setIndices(indices, totalVertices, updatable);
  27491. }
  27492. return this;
  27493. };
  27494. /**
  27495. * Update the current index buffer
  27496. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27497. * Returns the Mesh.
  27498. */
  27499. Mesh.prototype.updateIndices = function (indices, offset) {
  27500. if (!this._geometry) {
  27501. return this;
  27502. }
  27503. this._geometry.updateIndices(indices, offset);
  27504. return this;
  27505. };
  27506. /**
  27507. * Invert the geometry to move from a right handed system to a left handed one.
  27508. * Returns the Mesh.
  27509. */
  27510. Mesh.prototype.toLeftHanded = function () {
  27511. if (!this._geometry) {
  27512. return this;
  27513. }
  27514. this._geometry.toLeftHanded();
  27515. return this;
  27516. };
  27517. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27518. if (!this._geometry) {
  27519. return this;
  27520. }
  27521. var engine = this.getScene().getEngine();
  27522. // Wireframe
  27523. var indexToBind;
  27524. if (this._unIndexed) {
  27525. indexToBind = null;
  27526. }
  27527. else {
  27528. switch (fillMode) {
  27529. case BABYLON.Material.PointFillMode:
  27530. indexToBind = null;
  27531. break;
  27532. case BABYLON.Material.WireFrameFillMode:
  27533. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27534. break;
  27535. default:
  27536. case BABYLON.Material.TriangleFillMode:
  27537. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27538. break;
  27539. }
  27540. }
  27541. // VBOs
  27542. this._geometry._bind(effect, indexToBind);
  27543. return this;
  27544. };
  27545. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27546. if (alternate === void 0) { alternate = false; }
  27547. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27548. return this;
  27549. }
  27550. this.onBeforeDrawObservable.notifyObservers(this);
  27551. var scene = this.getScene();
  27552. var engine = scene.getEngine();
  27553. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27554. // or triangles as points
  27555. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27556. }
  27557. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27558. // Triangles as wireframe
  27559. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27560. }
  27561. else {
  27562. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27563. }
  27564. if (scene._isAlternateRenderingEnabled && !alternate) {
  27565. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27566. if (!effect || !scene.activeCamera) {
  27567. return this;
  27568. }
  27569. scene._switchToAlternateCameraConfiguration(true);
  27570. this._effectiveMaterial.bindView(effect);
  27571. this._effectiveMaterial.bindViewProjection(effect);
  27572. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27573. this._draw(subMesh, fillMode, instancesCount, true);
  27574. engine.setViewport(scene.activeCamera.viewport);
  27575. scene._switchToAlternateCameraConfiguration(false);
  27576. this._effectiveMaterial.bindView(effect);
  27577. this._effectiveMaterial.bindViewProjection(effect);
  27578. }
  27579. return this;
  27580. };
  27581. /**
  27582. * Registers for this mesh a javascript function called just before the rendering process.
  27583. * This function is passed the current mesh.
  27584. * Return the Mesh.
  27585. */
  27586. Mesh.prototype.registerBeforeRender = function (func) {
  27587. this.onBeforeRenderObservable.add(func);
  27588. return this;
  27589. };
  27590. /**
  27591. * Disposes a previously registered javascript function called before the rendering.
  27592. * This function is passed the current mesh.
  27593. * Returns the Mesh.
  27594. */
  27595. Mesh.prototype.unregisterBeforeRender = function (func) {
  27596. this.onBeforeRenderObservable.removeCallback(func);
  27597. return this;
  27598. };
  27599. /**
  27600. * Registers for this mesh a javascript function called just after the rendering is complete.
  27601. * This function is passed the current mesh.
  27602. * Returns the Mesh.
  27603. */
  27604. Mesh.prototype.registerAfterRender = function (func) {
  27605. this.onAfterRenderObservable.add(func);
  27606. return this;
  27607. };
  27608. /**
  27609. * Disposes a previously registered javascript function called after the rendering.
  27610. * This function is passed the current mesh.
  27611. * Return the Mesh.
  27612. */
  27613. Mesh.prototype.unregisterAfterRender = function (func) {
  27614. this.onAfterRenderObservable.removeCallback(func);
  27615. return this;
  27616. };
  27617. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27618. var scene = this.getScene();
  27619. this._batchCache.mustReturn = false;
  27620. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27621. this._batchCache.visibleInstances[subMeshId] = null;
  27622. if (this._visibleInstances) {
  27623. var currentRenderId = scene.getRenderId();
  27624. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27625. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27626. var selfRenderId = this._renderId;
  27627. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27628. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27629. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27630. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27631. }
  27632. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27633. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27634. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27635. this._batchCache.mustReturn = true;
  27636. return this._batchCache;
  27637. }
  27638. if (currentRenderId !== selfRenderId) {
  27639. this._batchCache.renderSelf[subMeshId] = false;
  27640. }
  27641. }
  27642. this._renderIdForInstances[subMeshId] = currentRenderId;
  27643. }
  27644. return this._batchCache;
  27645. };
  27646. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27647. var visibleInstances = batch.visibleInstances[subMesh._id];
  27648. if (!visibleInstances) {
  27649. return this;
  27650. }
  27651. var matricesCount = visibleInstances.length + 1;
  27652. var bufferSize = matricesCount * 16 * 4;
  27653. var currentInstancesBufferSize = this._instancesBufferSize;
  27654. var instancesBuffer = this._instancesBuffer;
  27655. while (this._instancesBufferSize < bufferSize) {
  27656. this._instancesBufferSize *= 2;
  27657. }
  27658. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27659. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27660. }
  27661. var offset = 0;
  27662. var instancesCount = 0;
  27663. var world = this.getWorldMatrix();
  27664. if (batch.renderSelf[subMesh._id]) {
  27665. world.copyToArray(this._instancesData, offset);
  27666. offset += 16;
  27667. instancesCount++;
  27668. }
  27669. if (visibleInstances) {
  27670. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27671. var instance = visibleInstances[instanceIndex];
  27672. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27673. offset += 16;
  27674. instancesCount++;
  27675. }
  27676. }
  27677. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27678. if (instancesBuffer) {
  27679. instancesBuffer.dispose();
  27680. }
  27681. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27682. this._instancesBuffer = instancesBuffer;
  27683. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27684. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27685. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27686. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27687. }
  27688. else {
  27689. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27690. }
  27691. this._bind(subMesh, effect, fillMode);
  27692. this._draw(subMesh, fillMode, instancesCount);
  27693. engine.unbindInstanceAttributes();
  27694. return this;
  27695. };
  27696. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27697. var scene = this.getScene();
  27698. var engine = scene.getEngine();
  27699. if (hardwareInstancedRendering) {
  27700. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27701. }
  27702. else {
  27703. if (batch.renderSelf[subMesh._id]) {
  27704. // Draw
  27705. if (onBeforeDraw) {
  27706. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27707. }
  27708. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27709. }
  27710. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27711. if (visibleInstancesForSubMesh) {
  27712. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27713. var instance = visibleInstancesForSubMesh[instanceIndex];
  27714. // World
  27715. var world = instance.getWorldMatrix();
  27716. if (onBeforeDraw) {
  27717. onBeforeDraw(true, world, effectiveMaterial);
  27718. }
  27719. // Draw
  27720. this._draw(subMesh, fillMode);
  27721. }
  27722. }
  27723. }
  27724. return this;
  27725. };
  27726. /**
  27727. * Triggers the draw call for the mesh.
  27728. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27729. * Returns the Mesh.
  27730. */
  27731. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27732. this.checkOcclusionQuery();
  27733. if (this._isOccluded) {
  27734. return this;
  27735. }
  27736. var scene = this.getScene();
  27737. // Managing instances
  27738. var batch = this._getInstancesRenderList(subMesh._id);
  27739. if (batch.mustReturn) {
  27740. return this;
  27741. }
  27742. // Checking geometry state
  27743. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27744. return this;
  27745. }
  27746. this.onBeforeRenderObservable.notifyObservers(this);
  27747. var engine = scene.getEngine();
  27748. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27749. // Material
  27750. var material = subMesh.getMaterial();
  27751. if (!material) {
  27752. return this;
  27753. }
  27754. this._effectiveMaterial = material;
  27755. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27756. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27757. return this;
  27758. }
  27759. }
  27760. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27761. return this;
  27762. }
  27763. // Alpha mode
  27764. if (enableAlphaMode) {
  27765. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27766. }
  27767. // Outline - step 1
  27768. var savedDepthWrite = engine.getDepthWrite();
  27769. if (this.renderOutline) {
  27770. engine.setDepthWrite(false);
  27771. scene.getOutlineRenderer().render(subMesh, batch);
  27772. engine.setDepthWrite(savedDepthWrite);
  27773. }
  27774. var effect;
  27775. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27776. effect = subMesh.effect;
  27777. }
  27778. else {
  27779. effect = this._effectiveMaterial.getEffect();
  27780. }
  27781. if (!effect) {
  27782. return this;
  27783. }
  27784. var sideOrientation = this.overrideMaterialSideOrientation;
  27785. if (sideOrientation == null) {
  27786. sideOrientation = this._effectiveMaterial.sideOrientation;
  27787. if (this._getWorldMatrixDeterminant() < 0) {
  27788. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27789. }
  27790. }
  27791. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27792. if (this._effectiveMaterial.forceDepthWrite) {
  27793. engine.setDepthWrite(true);
  27794. }
  27795. // Bind
  27796. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27797. if (!hardwareInstancedRendering) {
  27798. this._bind(subMesh, effect, fillMode);
  27799. }
  27800. var world = this.getWorldMatrix();
  27801. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27802. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27803. }
  27804. else {
  27805. this._effectiveMaterial.bind(world, this);
  27806. }
  27807. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27808. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27809. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27810. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27811. }
  27812. // Draw
  27813. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27814. // Unbind
  27815. this._effectiveMaterial.unbind();
  27816. // Outline - step 2
  27817. if (this.renderOutline && savedDepthWrite) {
  27818. engine.setDepthWrite(true);
  27819. engine.setColorWrite(false);
  27820. scene.getOutlineRenderer().render(subMesh, batch);
  27821. engine.setColorWrite(true);
  27822. }
  27823. // Overlay
  27824. if (this.renderOverlay) {
  27825. var currentMode = engine.getAlphaMode();
  27826. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27827. scene.getOutlineRenderer().render(subMesh, batch, true);
  27828. engine.setAlphaMode(currentMode);
  27829. }
  27830. this.onAfterRenderObservable.notifyObservers(this);
  27831. return this;
  27832. };
  27833. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27834. if (isInstance && effectiveMaterial) {
  27835. effectiveMaterial.bindOnlyWorldMatrix(world);
  27836. }
  27837. };
  27838. /**
  27839. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27840. */
  27841. Mesh.prototype.getEmittedParticleSystems = function () {
  27842. var results = new Array();
  27843. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27844. var particleSystem = this.getScene().particleSystems[index];
  27845. if (particleSystem.emitter === this) {
  27846. results.push(particleSystem);
  27847. }
  27848. }
  27849. return results;
  27850. };
  27851. /**
  27852. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27853. */
  27854. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27855. var results = new Array();
  27856. var descendants = this.getDescendants();
  27857. descendants.push(this);
  27858. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27859. var particleSystem = this.getScene().particleSystems[index];
  27860. var emitter = particleSystem.emitter;
  27861. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27862. results.push(particleSystem);
  27863. }
  27864. }
  27865. return results;
  27866. };
  27867. Mesh.prototype._checkDelayState = function () {
  27868. var scene = this.getScene();
  27869. if (this._geometry) {
  27870. this._geometry.load(scene);
  27871. }
  27872. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27873. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27874. this._queueLoad(scene);
  27875. }
  27876. return this;
  27877. };
  27878. Mesh.prototype._queueLoad = function (scene) {
  27879. var _this = this;
  27880. scene._addPendingData(this);
  27881. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27882. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27883. if (data instanceof ArrayBuffer) {
  27884. _this._delayLoadingFunction(data, _this);
  27885. }
  27886. else {
  27887. _this._delayLoadingFunction(JSON.parse(data), _this);
  27888. }
  27889. _this.instances.forEach(function (instance) {
  27890. instance._syncSubMeshes();
  27891. });
  27892. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27893. scene._removePendingData(_this);
  27894. }, function () { }, scene.database, getBinaryData);
  27895. return this;
  27896. };
  27897. /**
  27898. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27899. */
  27900. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27901. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27902. return false;
  27903. }
  27904. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27905. return false;
  27906. }
  27907. this._checkDelayState();
  27908. return true;
  27909. };
  27910. /**
  27911. * Sets the mesh material by the material or multiMaterial `id` property.
  27912. * The material `id` is a string identifying the material or the multiMaterial.
  27913. * This method returns the Mesh.
  27914. */
  27915. Mesh.prototype.setMaterialByID = function (id) {
  27916. var materials = this.getScene().materials;
  27917. var index;
  27918. for (index = materials.length - 1; index > -1; index--) {
  27919. if (materials[index].id === id) {
  27920. this.material = materials[index];
  27921. return this;
  27922. }
  27923. }
  27924. // Multi
  27925. var multiMaterials = this.getScene().multiMaterials;
  27926. for (index = multiMaterials.length - 1; index > -1; index--) {
  27927. if (multiMaterials[index].id === id) {
  27928. this.material = multiMaterials[index];
  27929. return this;
  27930. }
  27931. }
  27932. return this;
  27933. };
  27934. /**
  27935. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27936. */
  27937. Mesh.prototype.getAnimatables = function () {
  27938. var results = new Array();
  27939. if (this.material) {
  27940. results.push(this.material);
  27941. }
  27942. if (this.skeleton) {
  27943. results.push(this.skeleton);
  27944. }
  27945. return results;
  27946. };
  27947. /**
  27948. * Modifies the mesh geometry according to the passed transformation matrix.
  27949. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27950. * The mesh normals are modified accordingly the same transformation.
  27951. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27952. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27953. * Returns the Mesh.
  27954. */
  27955. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27956. // Position
  27957. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27958. return this;
  27959. }
  27960. var submeshes = this.subMeshes.splice(0);
  27961. this._resetPointsArrayCache();
  27962. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27963. var temp = new Array();
  27964. var index;
  27965. for (index = 0; index < data.length; index += 3) {
  27966. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27967. }
  27968. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27969. // Normals
  27970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27971. return this;
  27972. }
  27973. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27974. temp = [];
  27975. for (index = 0; index < data.length; index += 3) {
  27976. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27977. }
  27978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27979. // flip faces?
  27980. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27981. this.flipFaces();
  27982. }
  27983. // Restore submeshes
  27984. this.releaseSubMeshes();
  27985. this.subMeshes = submeshes;
  27986. return this;
  27987. };
  27988. /**
  27989. * Modifies the mesh geometry according to its own current World Matrix.
  27990. * The mesh World Matrix is then reset.
  27991. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27992. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27993. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27994. * Returns the Mesh.
  27995. */
  27996. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27997. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27998. this.scaling.copyFromFloats(1, 1, 1);
  27999. this.position.copyFromFloats(0, 0, 0);
  28000. this.rotation.copyFromFloats(0, 0, 0);
  28001. //only if quaternion is already set
  28002. if (this.rotationQuaternion) {
  28003. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28004. }
  28005. this._worldMatrix = BABYLON.Matrix.Identity();
  28006. return this;
  28007. };
  28008. Object.defineProperty(Mesh.prototype, "_positions", {
  28009. // Cache
  28010. get: function () {
  28011. if (this._geometry) {
  28012. return this._geometry._positions;
  28013. }
  28014. return null;
  28015. },
  28016. enumerable: true,
  28017. configurable: true
  28018. });
  28019. Mesh.prototype._resetPointsArrayCache = function () {
  28020. if (this._geometry) {
  28021. this._geometry._resetPointsArrayCache();
  28022. }
  28023. return this;
  28024. };
  28025. Mesh.prototype._generatePointsArray = function () {
  28026. if (this._geometry) {
  28027. return this._geometry._generatePointsArray();
  28028. }
  28029. return false;
  28030. };
  28031. /**
  28032. * Returns a new Mesh object generated from the current mesh properties.
  28033. * This method must not get confused with createInstance().
  28034. * The parameter `name` is a string, the name given to the new mesh.
  28035. * The optional parameter `newParent` can be any Node object (default `null`).
  28036. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28037. * 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.
  28038. */
  28039. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28040. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28041. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28042. };
  28043. /**
  28044. * Disposes the Mesh.
  28045. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28046. * Returns nothing.
  28047. */
  28048. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28049. var _this = this;
  28050. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28051. this.morphTargetManager = null;
  28052. if (this._geometry) {
  28053. this._geometry.releaseForMesh(this, true);
  28054. }
  28055. // Sources
  28056. var meshes = this.getScene().meshes;
  28057. meshes.forEach(function (abstractMesh) {
  28058. var mesh = abstractMesh;
  28059. if (mesh._source && mesh._source === _this) {
  28060. mesh._source = null;
  28061. }
  28062. });
  28063. this._source = null;
  28064. // Instances
  28065. if (this._instancesBuffer) {
  28066. this._instancesBuffer.dispose();
  28067. this._instancesBuffer = null;
  28068. }
  28069. while (this.instances.length) {
  28070. this.instances[0].dispose();
  28071. }
  28072. // Effect layers.
  28073. var effectLayers = this.getScene().effectLayers;
  28074. for (var i = 0; i < effectLayers.length; i++) {
  28075. var effectLayer = effectLayers[i];
  28076. if (effectLayer) {
  28077. effectLayer._disposeMesh(this);
  28078. }
  28079. }
  28080. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28081. };
  28082. /**
  28083. * Modifies the mesh geometry according to a displacement map.
  28084. * 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.
  28085. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28086. * This method returns nothing.
  28087. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28088. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28089. * 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.
  28090. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28091. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28092. *
  28093. * Returns the Mesh.
  28094. */
  28095. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28096. var _this = this;
  28097. var scene = this.getScene();
  28098. var onload = function (img) {
  28099. // Getting height map data
  28100. var canvas = document.createElement("canvas");
  28101. var context = canvas.getContext("2d");
  28102. var heightMapWidth = img.width;
  28103. var heightMapHeight = img.height;
  28104. canvas.width = heightMapWidth;
  28105. canvas.height = heightMapHeight;
  28106. context.drawImage(img, 0, 0);
  28107. // Create VertexData from map data
  28108. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28109. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28110. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28111. //execute success callback, if set
  28112. if (onSuccess) {
  28113. onSuccess(_this);
  28114. }
  28115. };
  28116. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28117. return this;
  28118. };
  28119. /**
  28120. * Modifies the mesh geometry according to a displacementMap buffer.
  28121. * 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.
  28122. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28123. * This method returns nothing.
  28124. * 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.
  28125. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28126. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28127. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28128. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28129. *
  28130. * Returns the Mesh.
  28131. */
  28132. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28133. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28134. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28135. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28136. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28137. return this;
  28138. }
  28139. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28140. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28141. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28142. var position = BABYLON.Vector3.Zero();
  28143. var normal = BABYLON.Vector3.Zero();
  28144. var uv = BABYLON.Vector2.Zero();
  28145. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28146. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28147. for (var index = 0; index < positions.length; index += 3) {
  28148. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28149. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28150. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28151. // Compute height
  28152. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28153. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28154. var pos = (u + v * heightMapWidth) * 4;
  28155. var r = buffer[pos] / 255.0;
  28156. var g = buffer[pos + 1] / 255.0;
  28157. var b = buffer[pos + 2] / 255.0;
  28158. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28159. normal.normalize();
  28160. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28161. position = position.add(normal);
  28162. position.toArray(positions, index);
  28163. }
  28164. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28165. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28166. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28167. return this;
  28168. };
  28169. /**
  28170. * Modify the mesh to get a flat shading rendering.
  28171. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28172. * This method returns the Mesh.
  28173. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28174. */
  28175. Mesh.prototype.convertToFlatShadedMesh = function () {
  28176. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28177. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28178. var kinds = this.getVerticesDataKinds();
  28179. var vbs = {};
  28180. var data = {};
  28181. var newdata = {};
  28182. var updatableNormals = false;
  28183. var kindIndex;
  28184. var kind;
  28185. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28186. kind = kinds[kindIndex];
  28187. var vertexBuffer = this.getVertexBuffer(kind);
  28188. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28189. updatableNormals = vertexBuffer.isUpdatable();
  28190. kinds.splice(kindIndex, 1);
  28191. kindIndex--;
  28192. continue;
  28193. }
  28194. vbs[kind] = vertexBuffer;
  28195. data[kind] = vbs[kind].getData();
  28196. newdata[kind] = [];
  28197. }
  28198. // Save previous submeshes
  28199. var previousSubmeshes = this.subMeshes.slice(0);
  28200. var indices = this.getIndices();
  28201. var totalIndices = this.getTotalIndices();
  28202. // Generating unique vertices per face
  28203. var index;
  28204. for (index = 0; index < totalIndices; index++) {
  28205. var vertexIndex = indices[index];
  28206. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28207. kind = kinds[kindIndex];
  28208. var stride = vbs[kind].getStrideSize();
  28209. for (var offset = 0; offset < stride; offset++) {
  28210. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28211. }
  28212. }
  28213. }
  28214. // Updating faces & normal
  28215. var normals = [];
  28216. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28217. for (index = 0; index < totalIndices; index += 3) {
  28218. indices[index] = index;
  28219. indices[index + 1] = index + 1;
  28220. indices[index + 2] = index + 2;
  28221. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28222. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28223. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28224. var p1p2 = p1.subtract(p2);
  28225. var p3p2 = p3.subtract(p2);
  28226. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28227. // Store same normals for every vertex
  28228. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28229. normals.push(normal.x);
  28230. normals.push(normal.y);
  28231. normals.push(normal.z);
  28232. }
  28233. }
  28234. this.setIndices(indices);
  28235. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28236. // Updating vertex buffers
  28237. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28238. kind = kinds[kindIndex];
  28239. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28240. }
  28241. // Updating submeshes
  28242. this.releaseSubMeshes();
  28243. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28244. var previousOne = previousSubmeshes[submeshIndex];
  28245. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28246. }
  28247. this.synchronizeInstances();
  28248. return this;
  28249. };
  28250. /**
  28251. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28252. * In other words, more vertices, no more indices and a single bigger VBO.
  28253. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28254. * Returns the Mesh.
  28255. */
  28256. Mesh.prototype.convertToUnIndexedMesh = function () {
  28257. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28258. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28259. var kinds = this.getVerticesDataKinds();
  28260. var vbs = {};
  28261. var data = {};
  28262. var newdata = {};
  28263. var kindIndex;
  28264. var kind;
  28265. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28266. kind = kinds[kindIndex];
  28267. var vertexBuffer = this.getVertexBuffer(kind);
  28268. vbs[kind] = vertexBuffer;
  28269. data[kind] = vbs[kind].getData();
  28270. newdata[kind] = [];
  28271. }
  28272. // Save previous submeshes
  28273. var previousSubmeshes = this.subMeshes.slice(0);
  28274. var indices = this.getIndices();
  28275. var totalIndices = this.getTotalIndices();
  28276. // Generating unique vertices per face
  28277. var index;
  28278. for (index = 0; index < totalIndices; index++) {
  28279. var vertexIndex = indices[index];
  28280. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28281. kind = kinds[kindIndex];
  28282. var stride = vbs[kind].getStrideSize();
  28283. for (var offset = 0; offset < stride; offset++) {
  28284. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28285. }
  28286. }
  28287. }
  28288. // Updating indices
  28289. for (index = 0; index < totalIndices; index += 3) {
  28290. indices[index] = index;
  28291. indices[index + 1] = index + 1;
  28292. indices[index + 2] = index + 2;
  28293. }
  28294. this.setIndices(indices);
  28295. // Updating vertex buffers
  28296. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28297. kind = kinds[kindIndex];
  28298. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28299. }
  28300. // Updating submeshes
  28301. this.releaseSubMeshes();
  28302. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28303. var previousOne = previousSubmeshes[submeshIndex];
  28304. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28305. }
  28306. this._unIndexed = true;
  28307. this.synchronizeInstances();
  28308. return this;
  28309. };
  28310. /**
  28311. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28312. * This method returns the Mesh.
  28313. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28314. */
  28315. Mesh.prototype.flipFaces = function (flipNormals) {
  28316. if (flipNormals === void 0) { flipNormals = false; }
  28317. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28318. var i;
  28319. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28320. for (i = 0; i < vertex_data.normals.length; i++) {
  28321. vertex_data.normals[i] *= -1;
  28322. }
  28323. }
  28324. if (vertex_data.indices) {
  28325. var temp;
  28326. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28327. // reassign indices
  28328. temp = vertex_data.indices[i + 1];
  28329. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28330. vertex_data.indices[i + 2] = temp;
  28331. }
  28332. }
  28333. vertex_data.applyToMesh(this);
  28334. return this;
  28335. };
  28336. // Instances
  28337. /**
  28338. * Creates a new InstancedMesh object from the mesh model.
  28339. * An instance shares the same properties and the same material than its model.
  28340. * Only these properties of each instance can then be set individually :
  28341. * - position
  28342. * - rotation
  28343. * - rotationQuaternion
  28344. * - setPivotMatrix
  28345. * - scaling
  28346. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28347. * Warning : this method is not supported for Line mesh and LineSystem
  28348. */
  28349. Mesh.prototype.createInstance = function (name) {
  28350. return new BABYLON.InstancedMesh(name, this);
  28351. };
  28352. /**
  28353. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28354. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28355. * This method returns the Mesh.
  28356. */
  28357. Mesh.prototype.synchronizeInstances = function () {
  28358. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28359. var instance = this.instances[instanceIndex];
  28360. instance._syncSubMeshes();
  28361. }
  28362. return this;
  28363. };
  28364. /**
  28365. * Simplify the mesh according to the given array of settings.
  28366. * Function will return immediately and will simplify async. It returns the Mesh.
  28367. * @param settings a collection of simplification settings.
  28368. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28369. * @param type the type of simplification to run.
  28370. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28371. */
  28372. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28373. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28374. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28375. this.getScene().simplificationQueue.addTask({
  28376. settings: settings,
  28377. parallelProcessing: parallelProcessing,
  28378. mesh: this,
  28379. simplificationType: simplificationType,
  28380. successCallback: successCallback
  28381. });
  28382. return this;
  28383. };
  28384. /**
  28385. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28386. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28387. * This should be used together with the simplification to avoid disappearing triangles.
  28388. * Returns the Mesh.
  28389. * @param successCallback an optional success callback to be called after the optimization finished.
  28390. */
  28391. Mesh.prototype.optimizeIndices = function (successCallback) {
  28392. var _this = this;
  28393. var indices = this.getIndices();
  28394. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28395. if (!positions || !indices) {
  28396. return this;
  28397. }
  28398. var vectorPositions = new Array();
  28399. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28400. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28401. }
  28402. var dupes = new Array();
  28403. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28404. var realPos = vectorPositions.length - 1 - iteration;
  28405. var testedPosition = vectorPositions[realPos];
  28406. for (var j = 0; j < realPos; ++j) {
  28407. var againstPosition = vectorPositions[j];
  28408. if (testedPosition.equals(againstPosition)) {
  28409. dupes[realPos] = j;
  28410. break;
  28411. }
  28412. }
  28413. }, function () {
  28414. for (var i = 0; i < indices.length; ++i) {
  28415. indices[i] = dupes[indices[i]] || indices[i];
  28416. }
  28417. //indices are now reordered
  28418. var originalSubMeshes = _this.subMeshes.slice(0);
  28419. _this.setIndices(indices);
  28420. _this.subMeshes = originalSubMeshes;
  28421. if (successCallback) {
  28422. successCallback(_this);
  28423. }
  28424. });
  28425. return this;
  28426. };
  28427. Mesh.prototype.serialize = function (serializationObject) {
  28428. serializationObject.name = this.name;
  28429. serializationObject.id = this.id;
  28430. serializationObject.type = this.getClassName();
  28431. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28432. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28433. }
  28434. serializationObject.position = this.position.asArray();
  28435. if (this.rotationQuaternion) {
  28436. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28437. }
  28438. else if (this.rotation) {
  28439. serializationObject.rotation = this.rotation.asArray();
  28440. }
  28441. serializationObject.scaling = this.scaling.asArray();
  28442. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28443. serializationObject.isEnabled = this.isEnabled(false);
  28444. serializationObject.isVisible = this.isVisible;
  28445. serializationObject.infiniteDistance = this.infiniteDistance;
  28446. serializationObject.pickable = this.isPickable;
  28447. serializationObject.receiveShadows = this.receiveShadows;
  28448. serializationObject.billboardMode = this.billboardMode;
  28449. serializationObject.visibility = this.visibility;
  28450. serializationObject.checkCollisions = this.checkCollisions;
  28451. serializationObject.isBlocker = this.isBlocker;
  28452. // Parent
  28453. if (this.parent) {
  28454. serializationObject.parentId = this.parent.id;
  28455. }
  28456. // Geometry
  28457. serializationObject.isUnIndexed = this.isUnIndexed;
  28458. var geometry = this._geometry;
  28459. if (geometry) {
  28460. var geometryId = geometry.id;
  28461. serializationObject.geometryId = geometryId;
  28462. // SubMeshes
  28463. serializationObject.subMeshes = [];
  28464. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28465. var subMesh = this.subMeshes[subIndex];
  28466. serializationObject.subMeshes.push({
  28467. materialIndex: subMesh.materialIndex,
  28468. verticesStart: subMesh.verticesStart,
  28469. verticesCount: subMesh.verticesCount,
  28470. indexStart: subMesh.indexStart,
  28471. indexCount: subMesh.indexCount
  28472. });
  28473. }
  28474. }
  28475. // Material
  28476. if (this.material) {
  28477. serializationObject.materialId = this.material.id;
  28478. }
  28479. else {
  28480. this.material = null;
  28481. }
  28482. // Morph targets
  28483. if (this.morphTargetManager) {
  28484. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28485. }
  28486. // Skeleton
  28487. if (this.skeleton) {
  28488. serializationObject.skeletonId = this.skeleton.id;
  28489. }
  28490. // Physics
  28491. //TODO implement correct serialization for physics impostors.
  28492. var impostor = this.getPhysicsImpostor();
  28493. if (impostor) {
  28494. serializationObject.physicsMass = impostor.getParam("mass");
  28495. serializationObject.physicsFriction = impostor.getParam("friction");
  28496. serializationObject.physicsRestitution = impostor.getParam("mass");
  28497. serializationObject.physicsImpostor = impostor.type;
  28498. }
  28499. // Metadata
  28500. if (this.metadata) {
  28501. serializationObject.metadata = this.metadata;
  28502. }
  28503. // Instances
  28504. serializationObject.instances = [];
  28505. for (var index = 0; index < this.instances.length; index++) {
  28506. var instance = this.instances[index];
  28507. var serializationInstance = {
  28508. name: instance.name,
  28509. id: instance.id,
  28510. position: instance.position.asArray(),
  28511. scaling: instance.scaling.asArray()
  28512. };
  28513. if (instance.rotationQuaternion) {
  28514. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28515. }
  28516. else if (instance.rotation) {
  28517. serializationInstance.rotation = instance.rotation.asArray();
  28518. }
  28519. serializationObject.instances.push(serializationInstance);
  28520. // Animations
  28521. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28522. serializationInstance.ranges = instance.serializeAnimationRanges();
  28523. }
  28524. //
  28525. // Animations
  28526. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28527. serializationObject.ranges = this.serializeAnimationRanges();
  28528. // Layer mask
  28529. serializationObject.layerMask = this.layerMask;
  28530. // Alpha
  28531. serializationObject.alphaIndex = this.alphaIndex;
  28532. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28533. // Overlay
  28534. serializationObject.overlayAlpha = this.overlayAlpha;
  28535. serializationObject.overlayColor = this.overlayColor.asArray();
  28536. serializationObject.renderOverlay = this.renderOverlay;
  28537. // Fog
  28538. serializationObject.applyFog = this.applyFog;
  28539. // Action Manager
  28540. if (this.actionManager) {
  28541. serializationObject.actions = this.actionManager.serialize(this.name);
  28542. }
  28543. };
  28544. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28545. if (!this.geometry) {
  28546. return;
  28547. }
  28548. this._markSubMeshesAsAttributesDirty();
  28549. var morphTargetManager = this._morphTargetManager;
  28550. if (morphTargetManager && morphTargetManager.vertexCount) {
  28551. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28552. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28553. this.morphTargetManager = null;
  28554. return;
  28555. }
  28556. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28557. var morphTarget = morphTargetManager.getActiveTarget(index);
  28558. var positions = morphTarget.getPositions();
  28559. if (!positions) {
  28560. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28561. return;
  28562. }
  28563. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28564. var normals = morphTarget.getNormals();
  28565. if (normals) {
  28566. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28567. }
  28568. var tangents = morphTarget.getTangents();
  28569. if (tangents) {
  28570. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28571. }
  28572. }
  28573. }
  28574. else {
  28575. var index = 0;
  28576. // Positions
  28577. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28578. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28579. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28580. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28581. }
  28582. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28583. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28584. }
  28585. index++;
  28586. }
  28587. }
  28588. };
  28589. // Statics
  28590. /**
  28591. * Returns a new Mesh object parsed from the source provided.
  28592. * The parameter `parsedMesh` is the source.
  28593. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28594. */
  28595. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28596. var mesh;
  28597. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28598. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28599. }
  28600. else {
  28601. mesh = new Mesh(parsedMesh.name, scene);
  28602. }
  28603. mesh.id = parsedMesh.id;
  28604. if (BABYLON.Tags) {
  28605. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28606. }
  28607. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28608. if (parsedMesh.metadata !== undefined) {
  28609. mesh.metadata = parsedMesh.metadata;
  28610. }
  28611. if (parsedMesh.rotationQuaternion) {
  28612. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28613. }
  28614. else if (parsedMesh.rotation) {
  28615. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28616. }
  28617. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28618. if (parsedMesh.localMatrix) {
  28619. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28620. }
  28621. else if (parsedMesh.pivotMatrix) {
  28622. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28623. }
  28624. mesh.setEnabled(parsedMesh.isEnabled);
  28625. mesh.isVisible = parsedMesh.isVisible;
  28626. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28627. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28628. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28629. if (parsedMesh.applyFog !== undefined) {
  28630. mesh.applyFog = parsedMesh.applyFog;
  28631. }
  28632. if (parsedMesh.pickable !== undefined) {
  28633. mesh.isPickable = parsedMesh.pickable;
  28634. }
  28635. if (parsedMesh.alphaIndex !== undefined) {
  28636. mesh.alphaIndex = parsedMesh.alphaIndex;
  28637. }
  28638. mesh.receiveShadows = parsedMesh.receiveShadows;
  28639. mesh.billboardMode = parsedMesh.billboardMode;
  28640. if (parsedMesh.visibility !== undefined) {
  28641. mesh.visibility = parsedMesh.visibility;
  28642. }
  28643. mesh.checkCollisions = parsedMesh.checkCollisions;
  28644. if (parsedMesh.isBlocker !== undefined) {
  28645. mesh.isBlocker = parsedMesh.isBlocker;
  28646. }
  28647. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28648. // freezeWorldMatrix
  28649. if (parsedMesh.freezeWorldMatrix) {
  28650. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28651. }
  28652. // Parent
  28653. if (parsedMesh.parentId) {
  28654. mesh._waitingParentId = parsedMesh.parentId;
  28655. }
  28656. // Actions
  28657. if (parsedMesh.actions !== undefined) {
  28658. mesh._waitingActions = parsedMesh.actions;
  28659. }
  28660. // Overlay
  28661. if (parsedMesh.overlayAlpha !== undefined) {
  28662. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28663. }
  28664. if (parsedMesh.overlayColor !== undefined) {
  28665. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28666. }
  28667. if (parsedMesh.renderOverlay !== undefined) {
  28668. mesh.renderOverlay = parsedMesh.renderOverlay;
  28669. }
  28670. // Geometry
  28671. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28672. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28673. if (parsedMesh.delayLoadingFile) {
  28674. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28675. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28676. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28677. if (parsedMesh._binaryInfo) {
  28678. mesh._binaryInfo = parsedMesh._binaryInfo;
  28679. }
  28680. mesh._delayInfo = [];
  28681. if (parsedMesh.hasUVs) {
  28682. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28683. }
  28684. if (parsedMesh.hasUVs2) {
  28685. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28686. }
  28687. if (parsedMesh.hasUVs3) {
  28688. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28689. }
  28690. if (parsedMesh.hasUVs4) {
  28691. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28692. }
  28693. if (parsedMesh.hasUVs5) {
  28694. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28695. }
  28696. if (parsedMesh.hasUVs6) {
  28697. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28698. }
  28699. if (parsedMesh.hasColors) {
  28700. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28701. }
  28702. if (parsedMesh.hasMatricesIndices) {
  28703. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28704. }
  28705. if (parsedMesh.hasMatricesWeights) {
  28706. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28707. }
  28708. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28709. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28710. mesh._checkDelayState();
  28711. }
  28712. }
  28713. else {
  28714. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28715. }
  28716. // Material
  28717. if (parsedMesh.materialId) {
  28718. mesh.setMaterialByID(parsedMesh.materialId);
  28719. }
  28720. else {
  28721. mesh.material = null;
  28722. }
  28723. // Morph targets
  28724. if (parsedMesh.morphTargetManagerId > -1) {
  28725. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28726. }
  28727. // Skeleton
  28728. if (parsedMesh.skeletonId > -1) {
  28729. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28730. if (parsedMesh.numBoneInfluencers) {
  28731. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28732. }
  28733. }
  28734. // Animations
  28735. if (parsedMesh.animations) {
  28736. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28737. var parsedAnimation = parsedMesh.animations[animationIndex];
  28738. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28739. }
  28740. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28741. }
  28742. if (parsedMesh.autoAnimate) {
  28743. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28744. }
  28745. // Layer Mask
  28746. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28747. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28748. }
  28749. else {
  28750. mesh.layerMask = 0x0FFFFFFF;
  28751. }
  28752. // Physics
  28753. if (parsedMesh.physicsImpostor) {
  28754. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28755. mass: parsedMesh.physicsMass,
  28756. friction: parsedMesh.physicsFriction,
  28757. restitution: parsedMesh.physicsRestitution
  28758. }, scene);
  28759. }
  28760. // Instances
  28761. if (parsedMesh.instances) {
  28762. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28763. var parsedInstance = parsedMesh.instances[index];
  28764. var instance = mesh.createInstance(parsedInstance.name);
  28765. if (parsedInstance.id) {
  28766. instance.id = parsedInstance.id;
  28767. }
  28768. if (BABYLON.Tags) {
  28769. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28770. }
  28771. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28772. if (parsedInstance.parentId) {
  28773. instance._waitingParentId = parsedInstance.parentId;
  28774. }
  28775. if (parsedInstance.rotationQuaternion) {
  28776. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28777. }
  28778. else if (parsedInstance.rotation) {
  28779. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28780. }
  28781. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28782. instance.checkCollisions = mesh.checkCollisions;
  28783. if (parsedMesh.animations) {
  28784. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28785. parsedAnimation = parsedMesh.animations[animationIndex];
  28786. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28787. }
  28788. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28789. }
  28790. }
  28791. }
  28792. return mesh;
  28793. };
  28794. /**
  28795. * Creates a ribbon mesh.
  28796. * Please consider using the same method from the MeshBuilder class instead.
  28797. * 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.
  28798. *
  28799. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28800. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28801. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28802. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28803. * 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.
  28804. * 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.
  28805. * 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
  28806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28809. */
  28810. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28811. if (closeArray === void 0) { closeArray = false; }
  28812. if (updatable === void 0) { updatable = false; }
  28813. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28814. pathArray: pathArray,
  28815. closeArray: closeArray,
  28816. closePath: closePath,
  28817. offset: offset,
  28818. updatable: updatable,
  28819. sideOrientation: sideOrientation,
  28820. instance: instance
  28821. }, scene);
  28822. };
  28823. /**
  28824. * Creates a plane polygonal mesh. By default, this is a disc.
  28825. * Please consider using the same method from the MeshBuilder class instead.
  28826. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28827. * 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.
  28828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28831. */
  28832. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28833. if (scene === void 0) { scene = null; }
  28834. var options = {
  28835. radius: radius,
  28836. tessellation: tessellation,
  28837. sideOrientation: sideOrientation,
  28838. updatable: updatable
  28839. };
  28840. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28841. };
  28842. /**
  28843. * Creates a box mesh.
  28844. * Please consider using the same method from the MeshBuilder class instead.
  28845. * The parameter `size` sets the size (float) of each box side (default 1).
  28846. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28847. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28849. */
  28850. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28851. if (scene === void 0) { scene = null; }
  28852. var options = {
  28853. size: size,
  28854. sideOrientation: sideOrientation,
  28855. updatable: updatable
  28856. };
  28857. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28858. };
  28859. /**
  28860. * Creates a sphere mesh.
  28861. * Please consider using the same method from the MeshBuilder class instead.
  28862. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28863. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28867. */
  28868. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28869. var options = {
  28870. segments: segments,
  28871. diameterX: diameter,
  28872. diameterY: diameter,
  28873. diameterZ: diameter,
  28874. sideOrientation: sideOrientation,
  28875. updatable: updatable
  28876. };
  28877. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28878. };
  28879. /**
  28880. * Creates a cylinder or a cone mesh.
  28881. * Please consider using the same method from the MeshBuilder class instead.
  28882. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28883. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28884. * 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.
  28885. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28886. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28887. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28888. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28890. */
  28891. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28892. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28893. if (scene !== undefined) {
  28894. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28895. updatable = scene;
  28896. }
  28897. scene = subdivisions;
  28898. subdivisions = 1;
  28899. }
  28900. var options = {
  28901. height: height,
  28902. diameterTop: diameterTop,
  28903. diameterBottom: diameterBottom,
  28904. tessellation: tessellation,
  28905. subdivisions: subdivisions,
  28906. sideOrientation: sideOrientation,
  28907. updatable: updatable
  28908. };
  28909. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28910. };
  28911. // Torus (Code from SharpDX.org)
  28912. /**
  28913. * Creates a torus mesh.
  28914. * Please consider using the same method from the MeshBuilder class instead.
  28915. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28916. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28917. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28921. */
  28922. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28923. var options = {
  28924. diameter: diameter,
  28925. thickness: thickness,
  28926. tessellation: tessellation,
  28927. sideOrientation: sideOrientation,
  28928. updatable: updatable
  28929. };
  28930. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28931. };
  28932. /**
  28933. * Creates a torus knot mesh.
  28934. * Please consider using the same method from the MeshBuilder class instead.
  28935. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28936. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28937. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28938. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28942. */
  28943. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28944. var options = {
  28945. radius: radius,
  28946. tube: tube,
  28947. radialSegments: radialSegments,
  28948. tubularSegments: tubularSegments,
  28949. p: p,
  28950. q: q,
  28951. sideOrientation: sideOrientation,
  28952. updatable: updatable
  28953. };
  28954. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28955. };
  28956. /**
  28957. * Creates a line mesh.
  28958. * Please consider using the same method from the MeshBuilder class instead.
  28959. * 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.
  28960. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28961. * The parameter `points` is an array successive Vector3.
  28962. * 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
  28963. * When updating an instance, remember that only point positions can change, not the number of points.
  28964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28965. */
  28966. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28967. if (scene === void 0) { scene = null; }
  28968. if (updatable === void 0) { updatable = false; }
  28969. if (instance === void 0) { instance = null; }
  28970. var options = {
  28971. points: points,
  28972. updatable: updatable,
  28973. instance: instance
  28974. };
  28975. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28976. };
  28977. /**
  28978. * Creates a dashed line mesh.
  28979. * Please consider using the same method from the MeshBuilder class instead.
  28980. * 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.
  28981. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28982. * The parameter `points` is an array successive Vector3.
  28983. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28984. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28985. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28986. * 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
  28987. * When updating an instance, remember that only point positions can change, not the number of points.
  28988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28989. */
  28990. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28991. if (scene === void 0) { scene = null; }
  28992. var options = {
  28993. points: points,
  28994. dashSize: dashSize,
  28995. gapSize: gapSize,
  28996. dashNb: dashNb,
  28997. updatable: updatable,
  28998. instance: instance
  28999. };
  29000. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29001. };
  29002. /**
  29003. * Creates a polygon mesh.
  29004. * Please consider using the same method from the MeshBuilder class instead.
  29005. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29006. * 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.
  29007. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29009. * Remember you can only change the shape positions, not their number when updating a polygon.
  29010. */
  29011. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29012. var options = {
  29013. shape: shape,
  29014. holes: holes,
  29015. updatable: updatable,
  29016. sideOrientation: sideOrientation
  29017. };
  29018. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29019. };
  29020. /**
  29021. * Creates an extruded polygon mesh, with depth in the Y direction.
  29022. * Please consider using the same method from the MeshBuilder class instead.
  29023. */
  29024. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29025. var options = {
  29026. shape: shape,
  29027. holes: holes,
  29028. depth: depth,
  29029. updatable: updatable,
  29030. sideOrientation: sideOrientation
  29031. };
  29032. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29033. };
  29034. /**
  29035. * Creates an extruded shape mesh.
  29036. * 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.
  29037. * Please consider using the same method from the MeshBuilder class instead.
  29038. *
  29039. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29040. * 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
  29041. * extruded along the Z axis.
  29042. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29043. * 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.
  29044. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29045. * 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
  29046. * 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
  29047. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29051. */
  29052. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29053. if (scene === void 0) { scene = null; }
  29054. var options = {
  29055. shape: shape,
  29056. path: path,
  29057. scale: scale,
  29058. rotation: rotation,
  29059. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29060. sideOrientation: sideOrientation,
  29061. instance: instance,
  29062. updatable: updatable
  29063. };
  29064. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29065. };
  29066. /**
  29067. * Creates an custom extruded shape mesh.
  29068. * 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.
  29069. * Please consider using the same method from the MeshBuilder class instead.
  29070. *
  29071. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29072. * 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
  29073. * extruded along the Z axis.
  29074. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29075. * 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
  29076. * and the distance of this point from the begining of the path :
  29077. * ```javascript
  29078. * var rotationFunction = function(i, distance) {
  29079. * // do things
  29080. * return rotationValue; }
  29081. * ```
  29082. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29083. * 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
  29084. * and the distance of this point from the begining of the path :
  29085. * ```javascript
  29086. * var scaleFunction = function(i, distance) {
  29087. * // do things
  29088. * return scaleValue;}
  29089. * ```
  29090. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29091. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29092. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29093. * 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
  29094. * 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
  29095. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29099. */
  29100. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29101. var options = {
  29102. shape: shape,
  29103. path: path,
  29104. scaleFunction: scaleFunction,
  29105. rotationFunction: rotationFunction,
  29106. ribbonCloseArray: ribbonCloseArray,
  29107. ribbonClosePath: ribbonClosePath,
  29108. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29109. sideOrientation: sideOrientation,
  29110. instance: instance,
  29111. updatable: updatable
  29112. };
  29113. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29114. };
  29115. /**
  29116. * Creates lathe mesh.
  29117. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29118. * Please consider using the same method from the MeshBuilder class instead.
  29119. * 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
  29120. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29121. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29122. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29126. */
  29127. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29128. var options = {
  29129. shape: shape,
  29130. radius: radius,
  29131. tessellation: tessellation,
  29132. sideOrientation: sideOrientation,
  29133. updatable: updatable
  29134. };
  29135. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29136. };
  29137. /**
  29138. * Creates a plane mesh.
  29139. * Please consider using the same method from the MeshBuilder class instead.
  29140. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29144. */
  29145. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29146. var options = {
  29147. size: size,
  29148. width: size,
  29149. height: size,
  29150. sideOrientation: sideOrientation,
  29151. updatable: updatable
  29152. };
  29153. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29154. };
  29155. /**
  29156. * Creates a ground mesh.
  29157. * Please consider using the same method from the MeshBuilder class instead.
  29158. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29159. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29161. */
  29162. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29163. var options = {
  29164. width: width,
  29165. height: height,
  29166. subdivisions: subdivisions,
  29167. updatable: updatable
  29168. };
  29169. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29170. };
  29171. /**
  29172. * Creates a tiled ground mesh.
  29173. * Please consider using the same method from the MeshBuilder class instead.
  29174. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29175. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29176. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29177. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29178. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29179. * numbers of subdivisions on the ground width and height of each tile.
  29180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29181. */
  29182. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29183. var options = {
  29184. xmin: xmin,
  29185. zmin: zmin,
  29186. xmax: xmax,
  29187. zmax: zmax,
  29188. subdivisions: subdivisions,
  29189. precision: precision,
  29190. updatable: updatable
  29191. };
  29192. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29193. };
  29194. /**
  29195. * Creates a ground mesh from a height map.
  29196. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29197. * Please consider using the same method from the MeshBuilder class instead.
  29198. * The parameter `url` sets the URL of the height map image resource.
  29199. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29200. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29201. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29202. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29203. * 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).
  29204. * This function is passed the newly built mesh :
  29205. * ```javascript
  29206. * function(mesh) { // do things
  29207. * return; }
  29208. * ```
  29209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29210. */
  29211. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29212. var options = {
  29213. width: width,
  29214. height: height,
  29215. subdivisions: subdivisions,
  29216. minHeight: minHeight,
  29217. maxHeight: maxHeight,
  29218. updatable: updatable,
  29219. onReady: onReady
  29220. };
  29221. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29222. };
  29223. /**
  29224. * Creates a tube mesh.
  29225. * 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.
  29226. * Please consider using the same method from the MeshBuilder class instead.
  29227. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29228. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29229. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29230. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29231. * 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.
  29232. * It must return a radius value (positive float) :
  29233. * ```javascript
  29234. * var radiusFunction = function(i, distance) {
  29235. * // do things
  29236. * return radius; }
  29237. * ```
  29238. * 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
  29239. * 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
  29240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29241. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29243. */
  29244. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29245. var options = {
  29246. path: path,
  29247. radius: radius,
  29248. tessellation: tessellation,
  29249. radiusFunction: radiusFunction,
  29250. arc: 1,
  29251. cap: cap,
  29252. updatable: updatable,
  29253. sideOrientation: sideOrientation,
  29254. instance: instance
  29255. };
  29256. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29257. };
  29258. /**
  29259. * Creates a polyhedron mesh.
  29260. * Please consider using the same method from the MeshBuilder class instead.
  29261. * 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
  29262. * to choose the wanted type.
  29263. * The parameter `size` (positive float, default 1) sets the polygon size.
  29264. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29265. * 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`.
  29266. * 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
  29267. * 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)`).
  29268. * 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
  29269. * 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.
  29270. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29273. */
  29274. Mesh.CreatePolyhedron = function (name, options, scene) {
  29275. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29276. };
  29277. /**
  29278. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29279. * Please consider using the same method from the MeshBuilder class instead.
  29280. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29281. * 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`).
  29282. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29283. * 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.
  29284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29287. */
  29288. Mesh.CreateIcoSphere = function (name, options, scene) {
  29289. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29290. };
  29291. /**
  29292. * Creates a decal mesh.
  29293. * Please consider using the same method from the MeshBuilder class instead.
  29294. * 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.
  29295. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29296. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29297. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29298. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29299. */
  29300. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29301. var options = {
  29302. position: position,
  29303. normal: normal,
  29304. size: size,
  29305. angle: angle
  29306. };
  29307. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29308. };
  29309. // Skeletons
  29310. /**
  29311. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29312. */
  29313. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29314. if (!this._sourcePositions) {
  29315. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29316. if (!source) {
  29317. return this._sourcePositions;
  29318. }
  29319. this._sourcePositions = new Float32Array(source);
  29320. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29321. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29322. }
  29323. }
  29324. return this._sourcePositions;
  29325. };
  29326. /**
  29327. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29328. */
  29329. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29330. if (!this._sourceNormals) {
  29331. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29332. if (!source) {
  29333. return this._sourceNormals;
  29334. }
  29335. this._sourceNormals = new Float32Array(source);
  29336. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29337. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29338. }
  29339. }
  29340. return this._sourceNormals;
  29341. };
  29342. /**
  29343. * Updates the vertex buffer by applying transformation from the bones.
  29344. * Returns the Mesh.
  29345. *
  29346. * @param {skeleton} skeleton to apply
  29347. */
  29348. Mesh.prototype.applySkeleton = function (skeleton) {
  29349. if (!this.geometry) {
  29350. return this;
  29351. }
  29352. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29353. return this;
  29354. }
  29355. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29356. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29357. return this;
  29358. }
  29359. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29360. return this;
  29361. }
  29362. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29363. return this;
  29364. }
  29365. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29366. return this;
  29367. }
  29368. if (!this._sourcePositions) {
  29369. var submeshes = this.subMeshes.slice();
  29370. this.setPositionsForCPUSkinning();
  29371. this.subMeshes = submeshes;
  29372. }
  29373. if (!this._sourceNormals) {
  29374. this.setNormalsForCPUSkinning();
  29375. }
  29376. // positionsData checks for not being Float32Array will only pass at most once
  29377. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29378. if (!positionsData) {
  29379. return this;
  29380. }
  29381. if (!(positionsData instanceof Float32Array)) {
  29382. positionsData = new Float32Array(positionsData);
  29383. }
  29384. // normalsData checks for not being Float32Array will only pass at most once
  29385. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29386. if (!normalsData) {
  29387. return this;
  29388. }
  29389. if (!(normalsData instanceof Float32Array)) {
  29390. normalsData = new Float32Array(normalsData);
  29391. }
  29392. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29393. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29394. if (!matricesWeightsData || !matricesIndicesData) {
  29395. return this;
  29396. }
  29397. var needExtras = this.numBoneInfluencers > 4;
  29398. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29399. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29400. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29401. var tempVector3 = BABYLON.Vector3.Zero();
  29402. var finalMatrix = new BABYLON.Matrix();
  29403. var tempMatrix = new BABYLON.Matrix();
  29404. var matWeightIdx = 0;
  29405. var inf;
  29406. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29407. var weight;
  29408. for (inf = 0; inf < 4; inf++) {
  29409. weight = matricesWeightsData[matWeightIdx + inf];
  29410. if (weight > 0) {
  29411. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29412. finalMatrix.addToSelf(tempMatrix);
  29413. }
  29414. else
  29415. break;
  29416. }
  29417. if (needExtras) {
  29418. for (inf = 0; inf < 4; inf++) {
  29419. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29420. if (weight > 0) {
  29421. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29422. finalMatrix.addToSelf(tempMatrix);
  29423. }
  29424. else
  29425. break;
  29426. }
  29427. }
  29428. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29429. tempVector3.toArray(positionsData, index);
  29430. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29431. tempVector3.toArray(normalsData, index);
  29432. finalMatrix.reset();
  29433. }
  29434. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29435. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29436. return this;
  29437. };
  29438. // Tools
  29439. /**
  29440. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29441. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29442. */
  29443. Mesh.MinMax = function (meshes) {
  29444. var minVector = null;
  29445. var maxVector = null;
  29446. meshes.forEach(function (mesh, index, array) {
  29447. var boundingInfo = mesh.getBoundingInfo();
  29448. var boundingBox = boundingInfo.boundingBox;
  29449. if (!minVector || !maxVector) {
  29450. minVector = boundingBox.minimumWorld;
  29451. maxVector = boundingBox.maximumWorld;
  29452. }
  29453. else {
  29454. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29455. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29456. }
  29457. });
  29458. if (!minVector || !maxVector) {
  29459. return {
  29460. min: BABYLON.Vector3.Zero(),
  29461. max: BABYLON.Vector3.Zero()
  29462. };
  29463. }
  29464. return {
  29465. min: minVector,
  29466. max: maxVector
  29467. };
  29468. };
  29469. /**
  29470. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29471. */
  29472. Mesh.Center = function (meshesOrMinMaxVector) {
  29473. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29474. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29475. };
  29476. /**
  29477. * Merge the array of meshes into a single mesh for performance reasons.
  29478. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29479. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29480. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29481. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29482. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29483. */
  29484. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29485. if (disposeSource === void 0) { disposeSource = true; }
  29486. var index;
  29487. if (!allow32BitsIndices) {
  29488. var totalVertices = 0;
  29489. // Counting vertices
  29490. for (index = 0; index < meshes.length; index++) {
  29491. if (meshes[index]) {
  29492. totalVertices += meshes[index].getTotalVertices();
  29493. if (totalVertices > 65536) {
  29494. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29495. return null;
  29496. }
  29497. }
  29498. }
  29499. }
  29500. // Merge
  29501. var vertexData = null;
  29502. var otherVertexData;
  29503. var indiceArray = new Array();
  29504. var source = null;
  29505. for (index = 0; index < meshes.length; index++) {
  29506. if (meshes[index]) {
  29507. meshes[index].computeWorldMatrix(true);
  29508. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29509. otherVertexData.transform(meshes[index].getWorldMatrix());
  29510. if (vertexData) {
  29511. vertexData.merge(otherVertexData);
  29512. }
  29513. else {
  29514. vertexData = otherVertexData;
  29515. source = meshes[index];
  29516. }
  29517. if (subdivideWithSubMeshes) {
  29518. indiceArray.push(meshes[index].getTotalIndices());
  29519. }
  29520. }
  29521. }
  29522. source = source;
  29523. if (!meshSubclass) {
  29524. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29525. }
  29526. vertexData.applyToMesh(meshSubclass);
  29527. // Setting properties
  29528. meshSubclass.material = source.material;
  29529. meshSubclass.checkCollisions = source.checkCollisions;
  29530. // Cleaning
  29531. if (disposeSource) {
  29532. for (index = 0; index < meshes.length; index++) {
  29533. if (meshes[index]) {
  29534. meshes[index].dispose();
  29535. }
  29536. }
  29537. }
  29538. // Subdivide
  29539. if (subdivideWithSubMeshes) {
  29540. //-- Suppresions du submesh global
  29541. meshSubclass.releaseSubMeshes();
  29542. index = 0;
  29543. var offset = 0;
  29544. //-- aplique la subdivision en fonction du tableau d'indices
  29545. while (index < indiceArray.length) {
  29546. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29547. offset += indiceArray[index];
  29548. index++;
  29549. }
  29550. }
  29551. return meshSubclass;
  29552. };
  29553. // Consts
  29554. Mesh._FRONTSIDE = 0;
  29555. Mesh._BACKSIDE = 1;
  29556. Mesh._DOUBLESIDE = 2;
  29557. Mesh._DEFAULTSIDE = 0;
  29558. Mesh._NO_CAP = 0;
  29559. Mesh._CAP_START = 1;
  29560. Mesh._CAP_END = 2;
  29561. Mesh._CAP_ALL = 3;
  29562. return Mesh;
  29563. }(BABYLON.AbstractMesh));
  29564. BABYLON.Mesh = Mesh;
  29565. })(BABYLON || (BABYLON = {}));
  29566. //# sourceMappingURL=babylon.mesh.js.map
  29567. var BABYLON;
  29568. (function (BABYLON) {
  29569. var BaseSubMesh = /** @class */ (function () {
  29570. function BaseSubMesh() {
  29571. }
  29572. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29573. get: function () {
  29574. return this._materialEffect;
  29575. },
  29576. enumerable: true,
  29577. configurable: true
  29578. });
  29579. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29580. if (defines === void 0) { defines = null; }
  29581. if (this._materialEffect === effect) {
  29582. if (!effect) {
  29583. this._materialDefines = null;
  29584. }
  29585. return;
  29586. }
  29587. this._materialDefines = defines;
  29588. this._materialEffect = effect;
  29589. };
  29590. return BaseSubMesh;
  29591. }());
  29592. BABYLON.BaseSubMesh = BaseSubMesh;
  29593. var SubMesh = /** @class */ (function (_super) {
  29594. __extends(SubMesh, _super);
  29595. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29596. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29597. var _this = _super.call(this) || this;
  29598. _this.materialIndex = materialIndex;
  29599. _this.verticesStart = verticesStart;
  29600. _this.verticesCount = verticesCount;
  29601. _this.indexStart = indexStart;
  29602. _this.indexCount = indexCount;
  29603. _this._renderId = 0;
  29604. _this._mesh = mesh;
  29605. _this._renderingMesh = renderingMesh || mesh;
  29606. mesh.subMeshes.push(_this);
  29607. _this._trianglePlanes = [];
  29608. _this._id = mesh.subMeshes.length - 1;
  29609. if (createBoundingBox) {
  29610. _this.refreshBoundingInfo();
  29611. mesh.computeWorldMatrix(true);
  29612. }
  29613. return _this;
  29614. }
  29615. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29616. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29617. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29618. };
  29619. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29620. get: function () {
  29621. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. /**
  29627. * Returns the submesh BoudingInfo object.
  29628. */
  29629. SubMesh.prototype.getBoundingInfo = function () {
  29630. if (this.IsGlobal) {
  29631. return this._mesh.getBoundingInfo();
  29632. }
  29633. return this._boundingInfo;
  29634. };
  29635. /**
  29636. * Sets the submesh BoundingInfo.
  29637. * Return the SubMesh.
  29638. */
  29639. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29640. this._boundingInfo = boundingInfo;
  29641. return this;
  29642. };
  29643. /**
  29644. * Returns the mesh of the current submesh.
  29645. */
  29646. SubMesh.prototype.getMesh = function () {
  29647. return this._mesh;
  29648. };
  29649. /**
  29650. * Returns the rendering mesh of the submesh.
  29651. */
  29652. SubMesh.prototype.getRenderingMesh = function () {
  29653. return this._renderingMesh;
  29654. };
  29655. /**
  29656. * Returns the submesh material.
  29657. */
  29658. SubMesh.prototype.getMaterial = function () {
  29659. var rootMaterial = this._renderingMesh.material;
  29660. if (rootMaterial === null || rootMaterial === undefined) {
  29661. return this._mesh.getScene().defaultMaterial;
  29662. }
  29663. else if (rootMaterial.getSubMaterial) {
  29664. var multiMaterial = rootMaterial;
  29665. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29666. if (this._currentMaterial !== effectiveMaterial) {
  29667. this._currentMaterial = effectiveMaterial;
  29668. this._materialDefines = null;
  29669. }
  29670. return effectiveMaterial;
  29671. }
  29672. return rootMaterial;
  29673. };
  29674. // Methods
  29675. /**
  29676. * Sets a new updated BoundingInfo object to the submesh.
  29677. * Returns the SubMesh.
  29678. */
  29679. SubMesh.prototype.refreshBoundingInfo = function () {
  29680. this._lastColliderWorldVertices = null;
  29681. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29682. return this;
  29683. }
  29684. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29685. if (!data) {
  29686. this._boundingInfo = this._mesh.getBoundingInfo();
  29687. return this;
  29688. }
  29689. var indices = this._renderingMesh.getIndices();
  29690. var extend;
  29691. //is this the only submesh?
  29692. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29693. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29694. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29695. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29696. }
  29697. else {
  29698. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29699. }
  29700. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29701. return this;
  29702. };
  29703. SubMesh.prototype._checkCollision = function (collider) {
  29704. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29705. return boundingInfo._checkCollision(collider);
  29706. };
  29707. /**
  29708. * Updates the submesh BoundingInfo.
  29709. * Returns the Submesh.
  29710. */
  29711. SubMesh.prototype.updateBoundingInfo = function (world) {
  29712. var boundingInfo = this.getBoundingInfo();
  29713. if (!boundingInfo) {
  29714. this.refreshBoundingInfo();
  29715. boundingInfo = this.getBoundingInfo();
  29716. }
  29717. boundingInfo.update(world);
  29718. return this;
  29719. };
  29720. /**
  29721. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29722. * Boolean returned.
  29723. */
  29724. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29725. var boundingInfo = this.getBoundingInfo();
  29726. if (!boundingInfo) {
  29727. return false;
  29728. }
  29729. return boundingInfo.isInFrustum(frustumPlanes);
  29730. };
  29731. /**
  29732. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29733. * Boolean returned.
  29734. */
  29735. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29736. var boundingInfo = this.getBoundingInfo();
  29737. if (!boundingInfo) {
  29738. return false;
  29739. }
  29740. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29741. };
  29742. /**
  29743. * Renders the submesh.
  29744. * Returns it.
  29745. */
  29746. SubMesh.prototype.render = function (enableAlphaMode) {
  29747. this._renderingMesh.render(this, enableAlphaMode);
  29748. return this;
  29749. };
  29750. /**
  29751. * Returns a new Index Buffer.
  29752. * Type returned : WebGLBuffer.
  29753. */
  29754. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29755. if (!this._linesIndexBuffer) {
  29756. var linesIndices = [];
  29757. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29758. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29759. }
  29760. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29761. this.linesIndexCount = linesIndices.length;
  29762. }
  29763. return this._linesIndexBuffer;
  29764. };
  29765. /**
  29766. * True is the passed Ray intersects the submesh bounding box.
  29767. * Boolean returned.
  29768. */
  29769. SubMesh.prototype.canIntersects = function (ray) {
  29770. var boundingInfo = this.getBoundingInfo();
  29771. if (!boundingInfo) {
  29772. return false;
  29773. }
  29774. return ray.intersectsBox(boundingInfo.boundingBox);
  29775. };
  29776. /**
  29777. * Returns an object IntersectionInfo.
  29778. */
  29779. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29780. var intersectInfo = null;
  29781. // LineMesh first as it's also a Mesh...
  29782. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29783. var lineMesh = this._mesh;
  29784. // Line test
  29785. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29786. var p0 = positions[indices[index]];
  29787. var p1 = positions[indices[index + 1]];
  29788. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29789. if (length < 0) {
  29790. continue;
  29791. }
  29792. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29793. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29794. if (fastCheck) {
  29795. break;
  29796. }
  29797. }
  29798. }
  29799. }
  29800. else {
  29801. // Triangles test
  29802. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29803. var p0 = positions[indices[index]];
  29804. var p1 = positions[indices[index + 1]];
  29805. var p2 = positions[indices[index + 2]];
  29806. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29807. if (currentIntersectInfo) {
  29808. if (currentIntersectInfo.distance < 0) {
  29809. continue;
  29810. }
  29811. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29812. intersectInfo = currentIntersectInfo;
  29813. intersectInfo.faceId = index / 3;
  29814. if (fastCheck) {
  29815. break;
  29816. }
  29817. }
  29818. }
  29819. }
  29820. }
  29821. return intersectInfo;
  29822. };
  29823. SubMesh.prototype._rebuild = function () {
  29824. if (this._linesIndexBuffer) {
  29825. this._linesIndexBuffer = null;
  29826. }
  29827. };
  29828. // Clone
  29829. /**
  29830. * Creates a new Submesh from the passed Mesh.
  29831. */
  29832. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29833. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29834. if (!this.IsGlobal) {
  29835. var boundingInfo = this.getBoundingInfo();
  29836. if (!boundingInfo) {
  29837. return result;
  29838. }
  29839. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29840. }
  29841. return result;
  29842. };
  29843. // Dispose
  29844. /**
  29845. * Disposes the Submesh.
  29846. * Returns nothing.
  29847. */
  29848. SubMesh.prototype.dispose = function () {
  29849. if (this._linesIndexBuffer) {
  29850. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29851. this._linesIndexBuffer = null;
  29852. }
  29853. // Remove from mesh
  29854. var index = this._mesh.subMeshes.indexOf(this);
  29855. this._mesh.subMeshes.splice(index, 1);
  29856. };
  29857. // Statics
  29858. /**
  29859. * Creates a new Submesh from the passed parameters :
  29860. * - materialIndex (integer) : the index of the main mesh material.
  29861. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29862. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29863. * - mesh (Mesh) : the main mesh to create the submesh from.
  29864. * - renderingMesh (optional Mesh) : rendering mesh.
  29865. */
  29866. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29867. var minVertexIndex = Number.MAX_VALUE;
  29868. var maxVertexIndex = -Number.MAX_VALUE;
  29869. renderingMesh = (renderingMesh || mesh);
  29870. var indices = renderingMesh.getIndices();
  29871. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29872. var vertexIndex = indices[index];
  29873. if (vertexIndex < minVertexIndex)
  29874. minVertexIndex = vertexIndex;
  29875. if (vertexIndex > maxVertexIndex)
  29876. maxVertexIndex = vertexIndex;
  29877. }
  29878. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29879. };
  29880. return SubMesh;
  29881. }(BaseSubMesh));
  29882. BABYLON.SubMesh = SubMesh;
  29883. })(BABYLON || (BABYLON = {}));
  29884. //# sourceMappingURL=babylon.subMesh.js.map
  29885. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29886. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29887. s = arguments[i];
  29888. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29889. t[p] = s[p];
  29890. }
  29891. return t;
  29892. };
  29893. var BABYLON;
  29894. (function (BABYLON) {
  29895. /**
  29896. * Manages the defines for the Material.
  29897. */
  29898. var MaterialDefines = /** @class */ (function () {
  29899. function MaterialDefines() {
  29900. this._isDirty = true;
  29901. this._areLightsDirty = true;
  29902. this._areAttributesDirty = true;
  29903. this._areTexturesDirty = true;
  29904. this._areFresnelDirty = true;
  29905. this._areMiscDirty = true;
  29906. this._areImageProcessingDirty = true;
  29907. this._normals = false;
  29908. this._uvs = false;
  29909. this._needNormals = false;
  29910. this._needUVs = false;
  29911. }
  29912. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29913. /**
  29914. * Specifies if the material needs to be re-calculated.
  29915. */
  29916. get: function () {
  29917. return this._isDirty;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. /**
  29923. * Marks the material to indicate that it has been re-calculated.
  29924. */
  29925. MaterialDefines.prototype.markAsProcessed = function () {
  29926. this._isDirty = false;
  29927. this._areAttributesDirty = false;
  29928. this._areTexturesDirty = false;
  29929. this._areFresnelDirty = false;
  29930. this._areLightsDirty = false;
  29931. this._areMiscDirty = false;
  29932. this._areImageProcessingDirty = false;
  29933. };
  29934. /**
  29935. * Marks the material to indicate that it needs to be re-calculated.
  29936. */
  29937. MaterialDefines.prototype.markAsUnprocessed = function () {
  29938. this._isDirty = true;
  29939. };
  29940. /**
  29941. * Marks the material to indicate all of its defines need to be re-calculated.
  29942. */
  29943. MaterialDefines.prototype.markAllAsDirty = function () {
  29944. this._areTexturesDirty = true;
  29945. this._areAttributesDirty = true;
  29946. this._areLightsDirty = true;
  29947. this._areFresnelDirty = true;
  29948. this._areMiscDirty = true;
  29949. this._areImageProcessingDirty = true;
  29950. this._isDirty = true;
  29951. };
  29952. /**
  29953. * Marks the material to indicate that image processing needs to be re-calculated.
  29954. */
  29955. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29956. this._areImageProcessingDirty = true;
  29957. this._isDirty = true;
  29958. };
  29959. /**
  29960. * Marks the material to indicate the lights need to be re-calculated.
  29961. */
  29962. MaterialDefines.prototype.markAsLightDirty = function () {
  29963. this._areLightsDirty = true;
  29964. this._isDirty = true;
  29965. };
  29966. /**
  29967. * Marks the attribute state as changed.
  29968. */
  29969. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29970. this._areAttributesDirty = true;
  29971. this._isDirty = true;
  29972. };
  29973. /**
  29974. * Marks the texture state as changed.
  29975. */
  29976. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29977. this._areTexturesDirty = true;
  29978. this._isDirty = true;
  29979. };
  29980. /**
  29981. * Marks the fresnel state as changed.
  29982. */
  29983. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29984. this._areFresnelDirty = true;
  29985. this._isDirty = true;
  29986. };
  29987. /**
  29988. * Marks the misc state as changed.
  29989. */
  29990. MaterialDefines.prototype.markAsMiscDirty = function () {
  29991. this._areMiscDirty = true;
  29992. this._isDirty = true;
  29993. };
  29994. /**
  29995. * Rebuilds the material defines.
  29996. */
  29997. MaterialDefines.prototype.rebuild = function () {
  29998. if (this._keys) {
  29999. delete this._keys;
  30000. }
  30001. this._keys = [];
  30002. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30003. var key = _a[_i];
  30004. if (key[0] === "_") {
  30005. continue;
  30006. }
  30007. this._keys.push(key);
  30008. }
  30009. };
  30010. /**
  30011. * Specifies if two material defines are equal.
  30012. * @param other - A material define instance to compare to.
  30013. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30014. */
  30015. MaterialDefines.prototype.isEqual = function (other) {
  30016. if (this._keys.length !== other._keys.length) {
  30017. return false;
  30018. }
  30019. for (var index = 0; index < this._keys.length; index++) {
  30020. var prop = this._keys[index];
  30021. if (this[prop] !== other[prop]) {
  30022. return false;
  30023. }
  30024. }
  30025. return true;
  30026. };
  30027. /**
  30028. * Clones this instance's defines to another instance.
  30029. * @param other - material defines to clone values to.
  30030. */
  30031. MaterialDefines.prototype.cloneTo = function (other) {
  30032. if (this._keys.length !== other._keys.length) {
  30033. other._keys = this._keys.slice(0);
  30034. }
  30035. for (var index = 0; index < this._keys.length; index++) {
  30036. var prop = this._keys[index];
  30037. other[prop] = this[prop];
  30038. }
  30039. };
  30040. /**
  30041. * Resets the material define values.
  30042. */
  30043. MaterialDefines.prototype.reset = function () {
  30044. for (var index = 0; index < this._keys.length; index++) {
  30045. var prop = this._keys[index];
  30046. if (typeof (this[prop]) === "number") {
  30047. this[prop] = 0;
  30048. }
  30049. else {
  30050. this[prop] = false;
  30051. }
  30052. }
  30053. };
  30054. /**
  30055. * Converts the material define values to a string.
  30056. * @returns - String of material define information.
  30057. */
  30058. MaterialDefines.prototype.toString = function () {
  30059. var result = "";
  30060. for (var index = 0; index < this._keys.length; index++) {
  30061. var prop = this._keys[index];
  30062. var value = this[prop];
  30063. if (typeof (value) === "number") {
  30064. result += "#define " + prop + " " + this[prop] + "\n";
  30065. }
  30066. else if (value) {
  30067. result += "#define " + prop + "\n";
  30068. }
  30069. }
  30070. return result;
  30071. };
  30072. return MaterialDefines;
  30073. }());
  30074. BABYLON.MaterialDefines = MaterialDefines;
  30075. /**
  30076. * This offers the main features of a material in BJS.
  30077. */
  30078. var Material = /** @class */ (function () {
  30079. /**
  30080. * Creates a material instance.
  30081. * @param name - The name of the material.
  30082. * @param scene - The BJS scene to reference.
  30083. * @param doNotAdd - Specifies if the material should be added to the scene.
  30084. */
  30085. function Material(name, scene, doNotAdd) {
  30086. /**
  30087. * Specifies if the ready state should be checked on each call.
  30088. */
  30089. this.checkReadyOnEveryCall = false;
  30090. /**
  30091. * Specifies if the ready state should be checked once.
  30092. */
  30093. this.checkReadyOnlyOnce = false;
  30094. /**
  30095. * The state of the material.
  30096. */
  30097. this.state = "";
  30098. /**
  30099. * The alpha value of the material.
  30100. */
  30101. this._alpha = 1.0;
  30102. /**
  30103. * Specifies if back face culling is enabled.
  30104. */
  30105. this._backFaceCulling = true;
  30106. /**
  30107. * Specifies if the material should be serialized.
  30108. */
  30109. this.doNotSerialize = false;
  30110. /**
  30111. * Specifies if the effect should be stored on sub meshes.
  30112. */
  30113. this.storeEffectOnSubMeshes = false;
  30114. /**
  30115. * An event triggered when the material is disposed.
  30116. * @type {BABYLON.Observable}
  30117. */
  30118. this.onDisposeObservable = new BABYLON.Observable();
  30119. /**
  30120. * An event triggered when the material is bound.
  30121. * @type {BABYLON.Observable}
  30122. */
  30123. this.onBindObservable = new BABYLON.Observable();
  30124. /**
  30125. * An event triggered when the material is unbound.
  30126. * @type {BABYLON.Observable}
  30127. */
  30128. this.onUnBindObservable = new BABYLON.Observable();
  30129. /**
  30130. * Stores the value of the alpha mode.
  30131. */
  30132. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30133. /**
  30134. * Stores the state of the need depth pre-pass value.
  30135. */
  30136. this._needDepthPrePass = false;
  30137. /**
  30138. * Specifies if depth writing should be disabled.
  30139. */
  30140. this.disableDepthWrite = false;
  30141. /**
  30142. * Specifies if depth writing should be forced.
  30143. */
  30144. this.forceDepthWrite = false;
  30145. /**
  30146. * Specifies if there should be a separate pass for culling.
  30147. */
  30148. this.separateCullingPass = false;
  30149. /**
  30150. * Stores the state specifing if fog should be enabled.
  30151. */
  30152. this._fogEnabled = true;
  30153. /**
  30154. * Stores the size of points.
  30155. */
  30156. this.pointSize = 1.0;
  30157. /**
  30158. * Stores the z offset value.
  30159. */
  30160. this.zOffset = 0;
  30161. /**
  30162. * Specifies if the material was previously ready.
  30163. */
  30164. this._wasPreviouslyReady = false;
  30165. /**
  30166. * Stores the fill mode state.
  30167. */
  30168. this._fillMode = Material.TriangleFillMode;
  30169. this.name = name;
  30170. this.id = name || BABYLON.Tools.RandomId();
  30171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30172. if (this._scene.useRightHandedSystem) {
  30173. this.sideOrientation = Material.ClockWiseSideOrientation;
  30174. }
  30175. else {
  30176. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30177. }
  30178. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30179. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30180. if (!doNotAdd) {
  30181. this._scene.materials.push(this);
  30182. }
  30183. }
  30184. Object.defineProperty(Material, "TriangleFillMode", {
  30185. /**
  30186. * Returns the triangle fill mode.
  30187. */
  30188. get: function () {
  30189. return Material._TriangleFillMode;
  30190. },
  30191. enumerable: true,
  30192. configurable: true
  30193. });
  30194. Object.defineProperty(Material, "WireFrameFillMode", {
  30195. /**
  30196. * Returns the wireframe mode.
  30197. */
  30198. get: function () {
  30199. return Material._WireFrameFillMode;
  30200. },
  30201. enumerable: true,
  30202. configurable: true
  30203. });
  30204. Object.defineProperty(Material, "PointFillMode", {
  30205. /**
  30206. * Returns the point fill mode.
  30207. */
  30208. get: function () {
  30209. return Material._PointFillMode;
  30210. },
  30211. enumerable: true,
  30212. configurable: true
  30213. });
  30214. Object.defineProperty(Material, "PointListDrawMode", {
  30215. /**
  30216. * Returns the point list draw mode.
  30217. */
  30218. get: function () {
  30219. return Material._PointListDrawMode;
  30220. },
  30221. enumerable: true,
  30222. configurable: true
  30223. });
  30224. Object.defineProperty(Material, "LineListDrawMode", {
  30225. /**
  30226. * Returns the line list draw mode.
  30227. */
  30228. get: function () {
  30229. return Material._LineListDrawMode;
  30230. },
  30231. enumerable: true,
  30232. configurable: true
  30233. });
  30234. Object.defineProperty(Material, "LineLoopDrawMode", {
  30235. /**
  30236. * Returns the line loop draw mode.
  30237. */
  30238. get: function () {
  30239. return Material._LineLoopDrawMode;
  30240. },
  30241. enumerable: true,
  30242. configurable: true
  30243. });
  30244. Object.defineProperty(Material, "LineStripDrawMode", {
  30245. /**
  30246. * Returns the line strip draw mode.
  30247. */
  30248. get: function () {
  30249. return Material._LineStripDrawMode;
  30250. },
  30251. enumerable: true,
  30252. configurable: true
  30253. });
  30254. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30255. /**
  30256. * Returns the triangle strip draw mode.
  30257. */
  30258. get: function () {
  30259. return Material._TriangleStripDrawMode;
  30260. },
  30261. enumerable: true,
  30262. configurable: true
  30263. });
  30264. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30265. /**
  30266. * Returns the triangle fan draw mode.
  30267. */
  30268. get: function () {
  30269. return Material._TriangleFanDrawMode;
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30275. /**
  30276. * Returns the clock-wise side orientation.
  30277. */
  30278. get: function () {
  30279. return Material._ClockWiseSideOrientation;
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30285. /**
  30286. * Returns the counter clock-wise side orientation.
  30287. */
  30288. get: function () {
  30289. return Material._CounterClockWiseSideOrientation;
  30290. },
  30291. enumerable: true,
  30292. configurable: true
  30293. });
  30294. Object.defineProperty(Material, "TextureDirtyFlag", {
  30295. /**
  30296. * Returns the dirty texture flag value.
  30297. */
  30298. get: function () {
  30299. return Material._TextureDirtyFlag;
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Object.defineProperty(Material, "LightDirtyFlag", {
  30305. /**
  30306. * Returns the dirty light flag value.
  30307. */
  30308. get: function () {
  30309. return Material._LightDirtyFlag;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30315. /**
  30316. * Returns the dirty fresnel flag value.
  30317. */
  30318. get: function () {
  30319. return Material._FresnelDirtyFlag;
  30320. },
  30321. enumerable: true,
  30322. configurable: true
  30323. });
  30324. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30325. /**
  30326. * Returns the dirty attributes flag value.
  30327. */
  30328. get: function () {
  30329. return Material._AttributesDirtyFlag;
  30330. },
  30331. enumerable: true,
  30332. configurable: true
  30333. });
  30334. Object.defineProperty(Material, "MiscDirtyFlag", {
  30335. /**
  30336. * Returns the dirty misc flag value.
  30337. */
  30338. get: function () {
  30339. return Material._MiscDirtyFlag;
  30340. },
  30341. enumerable: true,
  30342. configurable: true
  30343. });
  30344. Object.defineProperty(Material.prototype, "alpha", {
  30345. /**
  30346. * Gets the alpha value of the material.
  30347. */
  30348. get: function () {
  30349. return this._alpha;
  30350. },
  30351. /**
  30352. * Sets the alpha value of the material.
  30353. */
  30354. set: function (value) {
  30355. if (this._alpha === value) {
  30356. return;
  30357. }
  30358. this._alpha = value;
  30359. this.markAsDirty(Material.MiscDirtyFlag);
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30365. /**
  30366. * Gets the back-face culling state.
  30367. */
  30368. get: function () {
  30369. return this._backFaceCulling;
  30370. },
  30371. /**
  30372. * Sets the back-face culling state.
  30373. */
  30374. set: function (value) {
  30375. if (this._backFaceCulling === value) {
  30376. return;
  30377. }
  30378. this._backFaceCulling = value;
  30379. this.markAsDirty(Material.TextureDirtyFlag);
  30380. },
  30381. enumerable: true,
  30382. configurable: true
  30383. });
  30384. Object.defineProperty(Material.prototype, "onDispose", {
  30385. /**
  30386. * Called during a dispose event.
  30387. */
  30388. set: function (callback) {
  30389. if (this._onDisposeObserver) {
  30390. this.onDisposeObservable.remove(this._onDisposeObserver);
  30391. }
  30392. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. Object.defineProperty(Material.prototype, "onBind", {
  30398. /**
  30399. * Called during a bind event.
  30400. */
  30401. set: function (callback) {
  30402. if (this._onBindObserver) {
  30403. this.onBindObservable.remove(this._onBindObserver);
  30404. }
  30405. this._onBindObserver = this.onBindObservable.add(callback);
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. Object.defineProperty(Material.prototype, "alphaMode", {
  30411. /**
  30412. * Gets the value of the alpha mode.
  30413. */
  30414. get: function () {
  30415. return this._alphaMode;
  30416. },
  30417. /**
  30418. * Sets the value of the alpha mode.
  30419. */
  30420. set: function (value) {
  30421. if (this._alphaMode === value) {
  30422. return;
  30423. }
  30424. this._alphaMode = value;
  30425. this.markAsDirty(Material.TextureDirtyFlag);
  30426. },
  30427. enumerable: true,
  30428. configurable: true
  30429. });
  30430. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30431. /**
  30432. * Gets the depth pre-pass value.
  30433. */
  30434. get: function () {
  30435. return this._needDepthPrePass;
  30436. },
  30437. /**
  30438. * Sets the need depth pre-pass value.
  30439. */
  30440. set: function (value) {
  30441. if (this._needDepthPrePass === value) {
  30442. return;
  30443. }
  30444. this._needDepthPrePass = value;
  30445. if (this._needDepthPrePass) {
  30446. this.checkReadyOnEveryCall = true;
  30447. }
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. Object.defineProperty(Material.prototype, "fogEnabled", {
  30453. /**
  30454. * Gets the value of the fog enabled state.
  30455. */
  30456. get: function () {
  30457. return this._fogEnabled;
  30458. },
  30459. /**
  30460. * Sets the state for enabling fog.
  30461. */
  30462. set: function (value) {
  30463. if (this._fogEnabled === value) {
  30464. return;
  30465. }
  30466. this._fogEnabled = value;
  30467. this.markAsDirty(Material.MiscDirtyFlag);
  30468. },
  30469. enumerable: true,
  30470. configurable: true
  30471. });
  30472. Object.defineProperty(Material.prototype, "wireframe", {
  30473. /**
  30474. * Gets a value specifying if wireframe mode is enabled.
  30475. */
  30476. get: function () {
  30477. return this._fillMode === Material.WireFrameFillMode;
  30478. },
  30479. /**
  30480. * Sets the state of wireframe mode.
  30481. */
  30482. set: function (value) {
  30483. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30484. },
  30485. enumerable: true,
  30486. configurable: true
  30487. });
  30488. Object.defineProperty(Material.prototype, "pointsCloud", {
  30489. /**
  30490. * Gets the value specifying if point clouds are enabled.
  30491. */
  30492. get: function () {
  30493. return this._fillMode === Material.PointFillMode;
  30494. },
  30495. /**
  30496. * Sets the state of point cloud mode.
  30497. */
  30498. set: function (value) {
  30499. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30500. },
  30501. enumerable: true,
  30502. configurable: true
  30503. });
  30504. Object.defineProperty(Material.prototype, "fillMode", {
  30505. /**
  30506. * Gets the material fill mode.
  30507. */
  30508. get: function () {
  30509. return this._fillMode;
  30510. },
  30511. /**
  30512. * Sets the material fill mode.
  30513. */
  30514. set: function (value) {
  30515. if (this._fillMode === value) {
  30516. return;
  30517. }
  30518. this._fillMode = value;
  30519. this.markAsDirty(Material.MiscDirtyFlag);
  30520. },
  30521. enumerable: true,
  30522. configurable: true
  30523. });
  30524. /**
  30525. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30526. * subclasses should override adding information pertainent to themselves.
  30527. * @returns - String with material information.
  30528. */
  30529. Material.prototype.toString = function (fullDetails) {
  30530. var ret = "Name: " + this.name;
  30531. if (fullDetails) {
  30532. }
  30533. return ret;
  30534. };
  30535. /**
  30536. * Gets the class name of the material.
  30537. * @returns - String with the class name of the material.
  30538. */
  30539. Material.prototype.getClassName = function () {
  30540. return "Material";
  30541. };
  30542. Object.defineProperty(Material.prototype, "isFrozen", {
  30543. /**
  30544. * Specifies if updates for the material been locked.
  30545. */
  30546. get: function () {
  30547. return this.checkReadyOnlyOnce;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. /**
  30553. * Locks updates for the material.
  30554. */
  30555. Material.prototype.freeze = function () {
  30556. this.checkReadyOnlyOnce = true;
  30557. };
  30558. /**
  30559. * Unlocks updates for the material.
  30560. */
  30561. Material.prototype.unfreeze = function () {
  30562. this.checkReadyOnlyOnce = false;
  30563. };
  30564. /**
  30565. * Specifies if the material is ready to be used.
  30566. * @param mesh - BJS mesh.
  30567. * @param useInstances - Specifies if instances should be used.
  30568. * @returns - Boolean indicating if the material is ready to be used.
  30569. */
  30570. Material.prototype.isReady = function (mesh, useInstances) {
  30571. return true;
  30572. };
  30573. /**
  30574. * Specifies that the submesh is ready to be used.
  30575. * @param mesh - BJS mesh.
  30576. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30577. * @param useInstances - Specifies that instances should be used.
  30578. * @returns - boolean indicating that the submesh is ready or not.
  30579. */
  30580. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30581. return false;
  30582. };
  30583. /**
  30584. * Returns the material effect.
  30585. * @returns - Nullable material effect.
  30586. */
  30587. Material.prototype.getEffect = function () {
  30588. return this._effect;
  30589. };
  30590. /**
  30591. * Returns the BJS scene.
  30592. * @returns - BJS Scene.
  30593. */
  30594. Material.prototype.getScene = function () {
  30595. return this._scene;
  30596. };
  30597. /**
  30598. * Specifies if the material will require alpha blending
  30599. * @returns - Boolean specifying if alpha blending is needed.
  30600. */
  30601. Material.prototype.needAlphaBlending = function () {
  30602. return (this.alpha < 1.0);
  30603. };
  30604. /**
  30605. * Specifies if the mesh will require alpha blending.
  30606. * @param mesh - BJS mesh.
  30607. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30608. */
  30609. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30610. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30611. };
  30612. /**
  30613. * Specifies if this material should be rendered in alpha test mode.
  30614. * @returns - Boolean specifying if an alpha test is needed.
  30615. */
  30616. Material.prototype.needAlphaTesting = function () {
  30617. return false;
  30618. };
  30619. /**
  30620. * Gets the texture used for the alpha test.
  30621. * @returns - Nullable alpha test texture.
  30622. */
  30623. Material.prototype.getAlphaTestTexture = function () {
  30624. return null;
  30625. };
  30626. /**
  30627. * Marks the material to indicate that it needs to be re-calculated.
  30628. */
  30629. Material.prototype.markDirty = function () {
  30630. this._wasPreviouslyReady = false;
  30631. };
  30632. Material.prototype._preBind = function (effect, overrideOrientation) {
  30633. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30634. var engine = this._scene.getEngine();
  30635. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30636. var reverse = orientation === Material.ClockWiseSideOrientation;
  30637. engine.enableEffect(effect ? effect : this._effect);
  30638. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30639. return reverse;
  30640. };
  30641. /**
  30642. * Binds the material to the mesh.
  30643. * @param world - World transformation matrix.
  30644. * @param mesh - Mesh to bind the material to.
  30645. */
  30646. Material.prototype.bind = function (world, mesh) {
  30647. };
  30648. /**
  30649. * Binds the submesh to the material.
  30650. * @param world - World transformation matrix.
  30651. * @param mesh - Mesh containing the submesh.
  30652. * @param subMesh - Submesh to bind the material to.
  30653. */
  30654. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30655. };
  30656. /**
  30657. * Binds the world matrix to the material.
  30658. * @param world - World transformation matrix.
  30659. */
  30660. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30661. };
  30662. /**
  30663. * Binds the scene's uniform buffer to the effect.
  30664. * @param effect - Effect to bind to the scene uniform buffer.
  30665. * @param sceneUbo - Scene uniform buffer.
  30666. */
  30667. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30668. sceneUbo.bindToEffect(effect, "Scene");
  30669. };
  30670. /**
  30671. * Binds the view matrix to the effect.
  30672. * @param effect - Effect to bind the view matrix to.
  30673. */
  30674. Material.prototype.bindView = function (effect) {
  30675. if (!this._useUBO) {
  30676. effect.setMatrix("view", this.getScene().getViewMatrix());
  30677. }
  30678. else {
  30679. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30680. }
  30681. };
  30682. /**
  30683. * Binds the view projection matrix to the effect.
  30684. * @param effect - Effect to bind the view projection matrix to.
  30685. */
  30686. Material.prototype.bindViewProjection = function (effect) {
  30687. if (!this._useUBO) {
  30688. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30689. }
  30690. else {
  30691. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30692. }
  30693. };
  30694. /**
  30695. * Specifies if material alpha testing should be turned on for the mesh.
  30696. * @param mesh - BJS mesh.
  30697. */
  30698. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30699. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30700. };
  30701. /**
  30702. * Processes to execute after binding the material to a mesh.
  30703. * @param mesh - BJS mesh.
  30704. */
  30705. Material.prototype._afterBind = function (mesh) {
  30706. this._scene._cachedMaterial = this;
  30707. if (mesh) {
  30708. this._scene._cachedVisibility = mesh.visibility;
  30709. }
  30710. else {
  30711. this._scene._cachedVisibility = 1;
  30712. }
  30713. if (mesh) {
  30714. this.onBindObservable.notifyObservers(mesh);
  30715. }
  30716. if (this.disableDepthWrite) {
  30717. var engine = this._scene.getEngine();
  30718. this._cachedDepthWriteState = engine.getDepthWrite();
  30719. engine.setDepthWrite(false);
  30720. }
  30721. };
  30722. /**
  30723. * Unbinds the material from the mesh.
  30724. */
  30725. Material.prototype.unbind = function () {
  30726. this.onUnBindObservable.notifyObservers(this);
  30727. if (this.disableDepthWrite) {
  30728. var engine = this._scene.getEngine();
  30729. engine.setDepthWrite(this._cachedDepthWriteState);
  30730. }
  30731. };
  30732. /**
  30733. * Gets the active textures from the material.
  30734. * @returns - Array of textures.
  30735. */
  30736. Material.prototype.getActiveTextures = function () {
  30737. return [];
  30738. };
  30739. /**
  30740. * Specifies if the material uses a texture.
  30741. * @param texture - Texture to check against the material.
  30742. * @returns - Boolean specifying if the material uses the texture.
  30743. */
  30744. Material.prototype.hasTexture = function (texture) {
  30745. return false;
  30746. };
  30747. /**
  30748. * Makes a duplicate of the material, and gives it a new name.
  30749. * @param name - Name to call the duplicated material.
  30750. * @returns - Nullable cloned material
  30751. */
  30752. Material.prototype.clone = function (name) {
  30753. return null;
  30754. };
  30755. /**
  30756. * Gets the meshes bound to the material.
  30757. * @returns - Array of meshes bound to the material.
  30758. */
  30759. Material.prototype.getBindedMeshes = function () {
  30760. var result = new Array();
  30761. for (var index = 0; index < this._scene.meshes.length; index++) {
  30762. var mesh = this._scene.meshes[index];
  30763. if (mesh.material === this) {
  30764. result.push(mesh);
  30765. }
  30766. }
  30767. return result;
  30768. };
  30769. /**
  30770. * Force shader compilation
  30771. * @param mesh - BJS mesh.
  30772. * @param onCompiled - function to execute once the material is compiled.
  30773. * @param options - options to pass to this function.
  30774. */
  30775. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30776. var _this = this;
  30777. var localOptions = __assign({ clipPlane: false }, options);
  30778. var subMesh = new BABYLON.BaseSubMesh();
  30779. var scene = this.getScene();
  30780. var checkReady = function () {
  30781. if (!_this._scene || !_this._scene.getEngine()) {
  30782. return;
  30783. }
  30784. if (subMesh._materialDefines) {
  30785. subMesh._materialDefines._renderId = -1;
  30786. }
  30787. var clipPlaneState = scene.clipPlane;
  30788. if (localOptions.clipPlane) {
  30789. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30790. }
  30791. if (_this.storeEffectOnSubMeshes) {
  30792. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30793. if (onCompiled) {
  30794. onCompiled(_this);
  30795. }
  30796. }
  30797. else {
  30798. setTimeout(checkReady, 16);
  30799. }
  30800. }
  30801. else {
  30802. if (_this.isReady(mesh)) {
  30803. if (onCompiled) {
  30804. onCompiled(_this);
  30805. }
  30806. }
  30807. else {
  30808. setTimeout(checkReady, 16);
  30809. }
  30810. }
  30811. if (localOptions.clipPlane) {
  30812. scene.clipPlane = clipPlaneState;
  30813. }
  30814. };
  30815. checkReady();
  30816. };
  30817. /**
  30818. * Force shader compilation.
  30819. * @param mesh The mesh that will use this material
  30820. * @param options Additional options for compiling the shaders
  30821. * @returns A promise that resolves when the compilation completes
  30822. */
  30823. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30824. var _this = this;
  30825. return new Promise(function (resolve) {
  30826. _this.forceCompilation(mesh, function () {
  30827. resolve();
  30828. }, options);
  30829. });
  30830. };
  30831. /**
  30832. * Marks a define in the material to indicate that it needs to be re-computed.
  30833. * @param flag - Material define flag.
  30834. */
  30835. Material.prototype.markAsDirty = function (flag) {
  30836. if (flag & Material.TextureDirtyFlag) {
  30837. this._markAllSubMeshesAsTexturesDirty();
  30838. }
  30839. if (flag & Material.LightDirtyFlag) {
  30840. this._markAllSubMeshesAsLightsDirty();
  30841. }
  30842. if (flag & Material.FresnelDirtyFlag) {
  30843. this._markAllSubMeshesAsFresnelDirty();
  30844. }
  30845. if (flag & Material.AttributesDirtyFlag) {
  30846. this._markAllSubMeshesAsAttributesDirty();
  30847. }
  30848. if (flag & Material.MiscDirtyFlag) {
  30849. this._markAllSubMeshesAsMiscDirty();
  30850. }
  30851. this.getScene().resetCachedMaterial();
  30852. };
  30853. /**
  30854. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30855. * @param func - function which checks material defines against the submeshes.
  30856. */
  30857. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30858. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30859. var mesh = _a[_i];
  30860. if (!mesh.subMeshes) {
  30861. continue;
  30862. }
  30863. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30864. var subMesh = _c[_b];
  30865. if (subMesh.getMaterial() !== this) {
  30866. continue;
  30867. }
  30868. if (!subMesh._materialDefines) {
  30869. continue;
  30870. }
  30871. func(subMesh._materialDefines);
  30872. }
  30873. }
  30874. };
  30875. /**
  30876. * Indicates that image processing needs to be re-calculated for all submeshes.
  30877. */
  30878. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30879. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30880. };
  30881. /**
  30882. * Indicates that textures need to be re-calculated for all submeshes.
  30883. */
  30884. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30885. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30886. };
  30887. /**
  30888. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30889. */
  30890. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30891. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  30892. };
  30893. /**
  30894. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  30895. */
  30896. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  30897. this._markAllSubMeshesAsDirty(function (defines) {
  30898. defines.markAsFresnelDirty();
  30899. defines.markAsMiscDirty();
  30900. });
  30901. };
  30902. /**
  30903. * Indicates that lights need to be re-calculated for all submeshes.
  30904. */
  30905. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  30906. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  30907. };
  30908. /**
  30909. * Indicates that attributes need to be re-calculated for all submeshes.
  30910. */
  30911. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30912. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  30913. };
  30914. /**
  30915. * Indicates that misc needs to be re-calculated for all submeshes.
  30916. */
  30917. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  30918. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  30919. };
  30920. /**
  30921. * Indicates that textures and misc need to be re-calculated for all submeshes.
  30922. */
  30923. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  30924. this._markAllSubMeshesAsDirty(function (defines) {
  30925. defines.markAsTexturesDirty();
  30926. defines.markAsMiscDirty();
  30927. });
  30928. };
  30929. /**
  30930. * Disposes the material.
  30931. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  30932. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  30933. */
  30934. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30935. // Animations
  30936. this.getScene().stopAnimation(this);
  30937. // Remove from scene
  30938. var index = this._scene.materials.indexOf(this);
  30939. if (index >= 0) {
  30940. this._scene.materials.splice(index, 1);
  30941. }
  30942. // Remove from meshes
  30943. for (index = 0; index < this._scene.meshes.length; index++) {
  30944. var mesh = this._scene.meshes[index];
  30945. if (mesh.material === this) {
  30946. mesh.material = null;
  30947. if (mesh.geometry) {
  30948. var geometry = (mesh.geometry);
  30949. if (this.storeEffectOnSubMeshes) {
  30950. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  30951. var subMesh = _a[_i];
  30952. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  30953. if (forceDisposeEffect && subMesh._materialEffect) {
  30954. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  30955. }
  30956. }
  30957. }
  30958. else {
  30959. geometry._releaseVertexArrayObject(this._effect);
  30960. }
  30961. }
  30962. }
  30963. }
  30964. this._uniformBuffer.dispose();
  30965. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30966. if (forceDisposeEffect && this._effect) {
  30967. if (!this.storeEffectOnSubMeshes) {
  30968. this._scene.getEngine()._releaseEffect(this._effect);
  30969. }
  30970. this._effect = null;
  30971. }
  30972. // Callback
  30973. this.onDisposeObservable.notifyObservers(this);
  30974. this.onDisposeObservable.clear();
  30975. this.onBindObservable.clear();
  30976. this.onUnBindObservable.clear();
  30977. };
  30978. /**
  30979. * Serializes this material.
  30980. * @returns - serialized material object.
  30981. */
  30982. Material.prototype.serialize = function () {
  30983. return BABYLON.SerializationHelper.Serialize(this);
  30984. };
  30985. /**
  30986. * Creates a MultiMaterial from parse MultiMaterial data.
  30987. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  30988. * @param scene - BJS scene.
  30989. * @returns - MultiMaterial.
  30990. */
  30991. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  30992. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  30993. multiMaterial.id = parsedMultiMaterial.id;
  30994. if (BABYLON.Tags) {
  30995. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  30996. }
  30997. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  30998. var subMatId = parsedMultiMaterial.materials[matIndex];
  30999. if (subMatId) {
  31000. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31001. }
  31002. else {
  31003. multiMaterial.subMaterials.push(null);
  31004. }
  31005. }
  31006. return multiMaterial;
  31007. };
  31008. /**
  31009. * Creates a material from parsed material data.
  31010. * @param parsedMaterial - Parsed material data.
  31011. * @param scene - BJS scene.
  31012. * @param rootUrl - Root URL containing the material information.
  31013. * @returns - Parsed material.
  31014. */
  31015. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31016. if (!parsedMaterial.customType) {
  31017. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31018. }
  31019. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31020. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31021. if (!BABYLON.LegacyPBRMaterial) {
  31022. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31023. return;
  31024. }
  31025. }
  31026. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31027. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31028. ;
  31029. };
  31030. // Triangle views
  31031. Material._TriangleFillMode = 0;
  31032. Material._WireFrameFillMode = 1;
  31033. Material._PointFillMode = 2;
  31034. // Draw modes
  31035. Material._PointListDrawMode = 3;
  31036. Material._LineListDrawMode = 4;
  31037. Material._LineLoopDrawMode = 5;
  31038. Material._LineStripDrawMode = 6;
  31039. Material._TriangleStripDrawMode = 7;
  31040. Material._TriangleFanDrawMode = 8;
  31041. /**
  31042. * Stores the clock-wise side orientation.
  31043. */
  31044. Material._ClockWiseSideOrientation = 0;
  31045. /**
  31046. * Stores the counter clock-wise side orientation.
  31047. */
  31048. Material._CounterClockWiseSideOrientation = 1;
  31049. /**
  31050. * The dirty texture flag value.
  31051. */
  31052. Material._TextureDirtyFlag = 1;
  31053. /**
  31054. * The dirty light flag value.
  31055. */
  31056. Material._LightDirtyFlag = 2;
  31057. /**
  31058. * The dirty fresnel flag value.
  31059. */
  31060. Material._FresnelDirtyFlag = 4;
  31061. /**
  31062. * The dirty attribute flag value.
  31063. */
  31064. Material._AttributesDirtyFlag = 8;
  31065. /**
  31066. * The dirty misc flag value.
  31067. */
  31068. Material._MiscDirtyFlag = 16;
  31069. __decorate([
  31070. BABYLON.serialize()
  31071. ], Material.prototype, "id", void 0);
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], Material.prototype, "name", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Material.prototype, "state", void 0);
  31084. __decorate([
  31085. BABYLON.serialize("alpha")
  31086. ], Material.prototype, "_alpha", void 0);
  31087. __decorate([
  31088. BABYLON.serialize("backFaceCulling")
  31089. ], Material.prototype, "_backFaceCulling", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Material.prototype, "sideOrientation", void 0);
  31093. __decorate([
  31094. BABYLON.serialize("alphaMode")
  31095. ], Material.prototype, "_alphaMode", void 0);
  31096. __decorate([
  31097. BABYLON.serialize()
  31098. ], Material.prototype, "_needDepthPrePass", void 0);
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Material.prototype, "disableDepthWrite", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Material.prototype, "forceDepthWrite", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Material.prototype, "separateCullingPass", void 0);
  31108. __decorate([
  31109. BABYLON.serialize("fogEnabled")
  31110. ], Material.prototype, "_fogEnabled", void 0);
  31111. __decorate([
  31112. BABYLON.serialize()
  31113. ], Material.prototype, "pointSize", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], Material.prototype, "zOffset", void 0);
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], Material.prototype, "wireframe", null);
  31120. __decorate([
  31121. BABYLON.serialize()
  31122. ], Material.prototype, "pointsCloud", null);
  31123. __decorate([
  31124. BABYLON.serialize()
  31125. ], Material.prototype, "fillMode", null);
  31126. return Material;
  31127. }());
  31128. BABYLON.Material = Material;
  31129. })(BABYLON || (BABYLON = {}));
  31130. //# sourceMappingURL=babylon.material.js.map
  31131. var BABYLON;
  31132. (function (BABYLON) {
  31133. var UniformBuffer = /** @class */ (function () {
  31134. /**
  31135. * Uniform buffer objects.
  31136. *
  31137. * Handles blocks of uniform on the GPU.
  31138. *
  31139. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31140. *
  31141. * For more information, please refer to :
  31142. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31143. */
  31144. function UniformBuffer(engine, data, dynamic) {
  31145. this._engine = engine;
  31146. this._noUBO = !engine.supportsUniformBuffers;
  31147. this._dynamic = dynamic;
  31148. this._data = data || [];
  31149. this._uniformLocations = {};
  31150. this._uniformSizes = {};
  31151. this._uniformLocationPointer = 0;
  31152. this._needSync = false;
  31153. if (this._noUBO) {
  31154. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31155. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31156. this.updateFloat = this._updateFloatForEffect;
  31157. this.updateFloat2 = this._updateFloat2ForEffect;
  31158. this.updateFloat3 = this._updateFloat3ForEffect;
  31159. this.updateFloat4 = this._updateFloat4ForEffect;
  31160. this.updateMatrix = this._updateMatrixForEffect;
  31161. this.updateVector3 = this._updateVector3ForEffect;
  31162. this.updateVector4 = this._updateVector4ForEffect;
  31163. this.updateColor3 = this._updateColor3ForEffect;
  31164. this.updateColor4 = this._updateColor4ForEffect;
  31165. }
  31166. else {
  31167. this._engine._uniformBuffers.push(this);
  31168. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31169. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31170. this.updateFloat = this._updateFloatForUniform;
  31171. this.updateFloat2 = this._updateFloat2ForUniform;
  31172. this.updateFloat3 = this._updateFloat3ForUniform;
  31173. this.updateFloat4 = this._updateFloat4ForUniform;
  31174. this.updateMatrix = this._updateMatrixForUniform;
  31175. this.updateVector3 = this._updateVector3ForUniform;
  31176. this.updateVector4 = this._updateVector4ForUniform;
  31177. this.updateColor3 = this._updateColor3ForUniform;
  31178. this.updateColor4 = this._updateColor4ForUniform;
  31179. }
  31180. }
  31181. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31182. // Properties
  31183. /**
  31184. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31185. * or just falling back on setUniformXXX calls.
  31186. */
  31187. get: function () {
  31188. return !this._noUBO;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31194. /**
  31195. * Indicates if the WebGL underlying uniform buffer is in sync
  31196. * with the javascript cache data.
  31197. */
  31198. get: function () {
  31199. return !this._needSync;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. /**
  31205. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31206. * Also, a dynamic UniformBuffer will disable cache verification and always
  31207. * update the underlying WebGL uniform buffer to the GPU.
  31208. */
  31209. UniformBuffer.prototype.isDynamic = function () {
  31210. return this._dynamic !== undefined;
  31211. };
  31212. /**
  31213. * The data cache on JS side.
  31214. */
  31215. UniformBuffer.prototype.getData = function () {
  31216. return this._bufferData;
  31217. };
  31218. /**
  31219. * The underlying WebGL Uniform buffer.
  31220. */
  31221. UniformBuffer.prototype.getBuffer = function () {
  31222. return this._buffer;
  31223. };
  31224. /**
  31225. * std140 layout specifies how to align data within an UBO structure.
  31226. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31227. * for specs.
  31228. */
  31229. UniformBuffer.prototype._fillAlignment = function (size) {
  31230. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31231. // and 4x4 matrices
  31232. // TODO : change if other types are used
  31233. var alignment;
  31234. if (size <= 2) {
  31235. alignment = size;
  31236. }
  31237. else {
  31238. alignment = 4;
  31239. }
  31240. if ((this._uniformLocationPointer % alignment) !== 0) {
  31241. var oldPointer = this._uniformLocationPointer;
  31242. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31243. var diff = this._uniformLocationPointer - oldPointer;
  31244. for (var i = 0; i < diff; i++) {
  31245. this._data.push(0);
  31246. }
  31247. }
  31248. };
  31249. /**
  31250. * Adds an uniform in the buffer.
  31251. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31252. * for the layout to be correct !
  31253. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31254. * @param {number|number[]} size Data size, or data directly.
  31255. */
  31256. UniformBuffer.prototype.addUniform = function (name, size) {
  31257. if (this._noUBO) {
  31258. return;
  31259. }
  31260. if (this._uniformLocations[name] !== undefined) {
  31261. // Already existing uniform
  31262. return;
  31263. }
  31264. // This function must be called in the order of the shader layout !
  31265. // size can be the size of the uniform, or data directly
  31266. var data;
  31267. if (size instanceof Array) {
  31268. data = size;
  31269. size = data.length;
  31270. }
  31271. else {
  31272. size = size;
  31273. data = [];
  31274. // Fill with zeros
  31275. for (var i = 0; i < size; i++) {
  31276. data.push(0);
  31277. }
  31278. }
  31279. this._fillAlignment(size);
  31280. this._uniformSizes[name] = size;
  31281. this._uniformLocations[name] = this._uniformLocationPointer;
  31282. this._uniformLocationPointer += size;
  31283. for (var i = 0; i < size; i++) {
  31284. this._data.push(data[i]);
  31285. }
  31286. this._needSync = true;
  31287. };
  31288. /**
  31289. * Wrapper for addUniform.
  31290. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31291. * @param {Matrix} mat A 4x4 matrix.
  31292. */
  31293. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31294. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31295. };
  31296. /**
  31297. * Wrapper for addUniform.
  31298. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31299. * @param {number} x
  31300. * @param {number} y
  31301. */
  31302. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31303. var temp = [x, y];
  31304. this.addUniform(name, temp);
  31305. };
  31306. /**
  31307. * Wrapper for addUniform.
  31308. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31309. * @param {number} x
  31310. * @param {number} y
  31311. * @param {number} z
  31312. */
  31313. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31314. var temp = [x, y, z];
  31315. this.addUniform(name, temp);
  31316. };
  31317. /**
  31318. * Wrapper for addUniform.
  31319. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31320. * @param {Color3} color
  31321. */
  31322. UniformBuffer.prototype.addColor3 = function (name, color) {
  31323. var temp = new Array();
  31324. color.toArray(temp);
  31325. this.addUniform(name, temp);
  31326. };
  31327. /**
  31328. * Wrapper for addUniform.
  31329. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31330. * @param {Color3} color
  31331. * @param {number} alpha
  31332. */
  31333. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31334. var temp = new Array();
  31335. color.toArray(temp);
  31336. temp.push(alpha);
  31337. this.addUniform(name, temp);
  31338. };
  31339. /**
  31340. * Wrapper for addUniform.
  31341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31342. * @param {Vector3} vector
  31343. */
  31344. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31345. var temp = new Array();
  31346. vector.toArray(temp);
  31347. this.addUniform(name, temp);
  31348. };
  31349. /**
  31350. * Wrapper for addUniform.
  31351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31352. */
  31353. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31354. this.addUniform(name, 12);
  31355. };
  31356. /**
  31357. * Wrapper for addUniform.
  31358. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31359. */
  31360. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31361. this.addUniform(name, 8);
  31362. };
  31363. /**
  31364. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31365. */
  31366. UniformBuffer.prototype.create = function () {
  31367. if (this._noUBO) {
  31368. return;
  31369. }
  31370. if (this._buffer) {
  31371. return; // nothing to do
  31372. }
  31373. // See spec, alignment must be filled as a vec4
  31374. this._fillAlignment(4);
  31375. this._bufferData = new Float32Array(this._data);
  31376. this._rebuild();
  31377. this._needSync = true;
  31378. };
  31379. UniformBuffer.prototype._rebuild = function () {
  31380. if (this._noUBO) {
  31381. return;
  31382. }
  31383. if (this._dynamic) {
  31384. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31385. }
  31386. else {
  31387. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31388. }
  31389. };
  31390. /**
  31391. * Updates the WebGL Uniform Buffer on the GPU.
  31392. * If the `dynamic` flag is set to true, no cache comparison is done.
  31393. * Otherwise, the buffer will be updated only if the cache differs.
  31394. */
  31395. UniformBuffer.prototype.update = function () {
  31396. if (!this._buffer) {
  31397. this.create();
  31398. return;
  31399. }
  31400. if (!this._dynamic && !this._needSync) {
  31401. return;
  31402. }
  31403. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31404. this._needSync = false;
  31405. };
  31406. /**
  31407. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31408. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31409. * @param {number[]|Float32Array} data Flattened data
  31410. * @param {number} size Size of the data.
  31411. */
  31412. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31413. var location = this._uniformLocations[uniformName];
  31414. if (location === undefined) {
  31415. if (this._buffer) {
  31416. // Cannot add an uniform if the buffer is already created
  31417. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31418. return;
  31419. }
  31420. this.addUniform(uniformName, size);
  31421. location = this._uniformLocations[uniformName];
  31422. }
  31423. if (!this._buffer) {
  31424. this.create();
  31425. }
  31426. if (!this._dynamic) {
  31427. // Cache for static uniform buffers
  31428. var changed = false;
  31429. for (var i = 0; i < size; i++) {
  31430. if (this._bufferData[location + i] !== data[i]) {
  31431. changed = true;
  31432. this._bufferData[location + i] = data[i];
  31433. }
  31434. }
  31435. this._needSync = this._needSync || changed;
  31436. }
  31437. else {
  31438. // No cache for dynamic
  31439. for (var i = 0; i < size; i++) {
  31440. this._bufferData[location + i] = data[i];
  31441. }
  31442. }
  31443. };
  31444. // Update methods
  31445. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31446. // To match std140, matrix must be realigned
  31447. for (var i = 0; i < 3; i++) {
  31448. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31449. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31450. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31451. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31452. }
  31453. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31454. };
  31455. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31456. this._currentEffect.setMatrix3x3(name, matrix);
  31457. };
  31458. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31459. this._currentEffect.setMatrix2x2(name, matrix);
  31460. };
  31461. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31462. // To match std140, matrix must be realigned
  31463. for (var i = 0; i < 2; i++) {
  31464. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31465. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31466. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31467. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31468. }
  31469. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31470. };
  31471. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31472. this._currentEffect.setFloat(name, x);
  31473. };
  31474. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31475. UniformBuffer._tempBuffer[0] = x;
  31476. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31477. };
  31478. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31479. if (suffix === void 0) { suffix = ""; }
  31480. this._currentEffect.setFloat2(name + suffix, x, y);
  31481. };
  31482. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31483. if (suffix === void 0) { suffix = ""; }
  31484. UniformBuffer._tempBuffer[0] = x;
  31485. UniformBuffer._tempBuffer[1] = y;
  31486. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31487. };
  31488. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31489. if (suffix === void 0) { suffix = ""; }
  31490. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31491. };
  31492. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31493. if (suffix === void 0) { suffix = ""; }
  31494. UniformBuffer._tempBuffer[0] = x;
  31495. UniformBuffer._tempBuffer[1] = y;
  31496. UniformBuffer._tempBuffer[2] = z;
  31497. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31498. };
  31499. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31500. if (suffix === void 0) { suffix = ""; }
  31501. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31502. };
  31503. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31504. if (suffix === void 0) { suffix = ""; }
  31505. UniformBuffer._tempBuffer[0] = x;
  31506. UniformBuffer._tempBuffer[1] = y;
  31507. UniformBuffer._tempBuffer[2] = z;
  31508. UniformBuffer._tempBuffer[3] = w;
  31509. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31510. };
  31511. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31512. this._currentEffect.setMatrix(name, mat);
  31513. };
  31514. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31515. this.updateUniform(name, mat.toArray(), 16);
  31516. };
  31517. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31518. this._currentEffect.setVector3(name, vector);
  31519. };
  31520. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31521. vector.toArray(UniformBuffer._tempBuffer);
  31522. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31523. };
  31524. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31525. this._currentEffect.setVector4(name, vector);
  31526. };
  31527. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31528. vector.toArray(UniformBuffer._tempBuffer);
  31529. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31530. };
  31531. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31532. if (suffix === void 0) { suffix = ""; }
  31533. this._currentEffect.setColor3(name + suffix, color);
  31534. };
  31535. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31536. if (suffix === void 0) { suffix = ""; }
  31537. color.toArray(UniformBuffer._tempBuffer);
  31538. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31539. };
  31540. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31541. if (suffix === void 0) { suffix = ""; }
  31542. this._currentEffect.setColor4(name + suffix, color, alpha);
  31543. };
  31544. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31545. if (suffix === void 0) { suffix = ""; }
  31546. color.toArray(UniformBuffer._tempBuffer);
  31547. UniformBuffer._tempBuffer[3] = alpha;
  31548. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31549. };
  31550. /**
  31551. * Sets a sampler uniform on the effect.
  31552. * @param {string} name Name of the sampler.
  31553. * @param {Texture} texture
  31554. */
  31555. UniformBuffer.prototype.setTexture = function (name, texture) {
  31556. this._currentEffect.setTexture(name, texture);
  31557. };
  31558. /**
  31559. * Directly updates the value of the uniform in the cache AND on the GPU.
  31560. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31561. * @param {number[]|Float32Array} data Flattened data
  31562. */
  31563. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31564. this.updateUniform(uniformName, data, data.length);
  31565. this.update();
  31566. };
  31567. /**
  31568. * Binds this uniform buffer to an effect.
  31569. * @param {Effect} effect
  31570. * @param {string} name Name of the uniform block in the shader.
  31571. */
  31572. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31573. this._currentEffect = effect;
  31574. if (this._noUBO || !this._buffer) {
  31575. return;
  31576. }
  31577. effect.bindUniformBuffer(this._buffer, name);
  31578. };
  31579. /**
  31580. * Disposes the uniform buffer.
  31581. */
  31582. UniformBuffer.prototype.dispose = function () {
  31583. if (this._noUBO) {
  31584. return;
  31585. }
  31586. var index = this._engine._uniformBuffers.indexOf(this);
  31587. if (index !== -1) {
  31588. this._engine._uniformBuffers.splice(index, 1);
  31589. }
  31590. if (!this._buffer) {
  31591. return;
  31592. }
  31593. if (this._engine._releaseBuffer(this._buffer)) {
  31594. this._buffer = null;
  31595. }
  31596. };
  31597. // Pool for avoiding memory leaks
  31598. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31599. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31600. return UniformBuffer;
  31601. }());
  31602. BABYLON.UniformBuffer = UniformBuffer;
  31603. })(BABYLON || (BABYLON = {}));
  31604. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31605. var BABYLON;
  31606. (function (BABYLON) {
  31607. var VertexData = /** @class */ (function () {
  31608. function VertexData() {
  31609. }
  31610. VertexData.prototype.set = function (data, kind) {
  31611. switch (kind) {
  31612. case BABYLON.VertexBuffer.PositionKind:
  31613. this.positions = data;
  31614. break;
  31615. case BABYLON.VertexBuffer.NormalKind:
  31616. this.normals = data;
  31617. break;
  31618. case BABYLON.VertexBuffer.TangentKind:
  31619. this.tangents = data;
  31620. break;
  31621. case BABYLON.VertexBuffer.UVKind:
  31622. this.uvs = data;
  31623. break;
  31624. case BABYLON.VertexBuffer.UV2Kind:
  31625. this.uvs2 = data;
  31626. break;
  31627. case BABYLON.VertexBuffer.UV3Kind:
  31628. this.uvs3 = data;
  31629. break;
  31630. case BABYLON.VertexBuffer.UV4Kind:
  31631. this.uvs4 = data;
  31632. break;
  31633. case BABYLON.VertexBuffer.UV5Kind:
  31634. this.uvs5 = data;
  31635. break;
  31636. case BABYLON.VertexBuffer.UV6Kind:
  31637. this.uvs6 = data;
  31638. break;
  31639. case BABYLON.VertexBuffer.ColorKind:
  31640. this.colors = data;
  31641. break;
  31642. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31643. this.matricesIndices = data;
  31644. break;
  31645. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31646. this.matricesWeights = data;
  31647. break;
  31648. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31649. this.matricesIndicesExtra = data;
  31650. break;
  31651. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31652. this.matricesWeightsExtra = data;
  31653. break;
  31654. }
  31655. };
  31656. /**
  31657. * Associates the vertexData to the passed Mesh.
  31658. * Sets it as updatable or not (default `false`).
  31659. * Returns the VertexData.
  31660. */
  31661. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31662. this._applyTo(mesh, updatable);
  31663. return this;
  31664. };
  31665. /**
  31666. * Associates the vertexData to the passed Geometry.
  31667. * Sets it as updatable or not (default `false`).
  31668. * Returns the VertexData.
  31669. */
  31670. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31671. this._applyTo(geometry, updatable);
  31672. return this;
  31673. };
  31674. /**
  31675. * Updates the associated mesh.
  31676. * Returns the VertexData.
  31677. */
  31678. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31679. this._update(mesh);
  31680. return this;
  31681. };
  31682. /**
  31683. * Updates the associated geometry.
  31684. * Returns the VertexData.
  31685. */
  31686. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31687. this._update(geometry);
  31688. return this;
  31689. };
  31690. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31691. if (updatable === void 0) { updatable = false; }
  31692. if (this.positions) {
  31693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31694. }
  31695. if (this.normals) {
  31696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31697. }
  31698. if (this.tangents) {
  31699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31700. }
  31701. if (this.uvs) {
  31702. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31703. }
  31704. if (this.uvs2) {
  31705. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31706. }
  31707. if (this.uvs3) {
  31708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31709. }
  31710. if (this.uvs4) {
  31711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31712. }
  31713. if (this.uvs5) {
  31714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31715. }
  31716. if (this.uvs6) {
  31717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31718. }
  31719. if (this.colors) {
  31720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31721. }
  31722. if (this.matricesIndices) {
  31723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31724. }
  31725. if (this.matricesWeights) {
  31726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31727. }
  31728. if (this.matricesIndicesExtra) {
  31729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31730. }
  31731. if (this.matricesWeightsExtra) {
  31732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31733. }
  31734. if (this.indices) {
  31735. meshOrGeometry.setIndices(this.indices, null, updatable);
  31736. }
  31737. return this;
  31738. };
  31739. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31740. if (this.positions) {
  31741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31742. }
  31743. if (this.normals) {
  31744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31745. }
  31746. if (this.tangents) {
  31747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31748. }
  31749. if (this.uvs) {
  31750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31751. }
  31752. if (this.uvs2) {
  31753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31754. }
  31755. if (this.uvs3) {
  31756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31757. }
  31758. if (this.uvs4) {
  31759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31760. }
  31761. if (this.uvs5) {
  31762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31763. }
  31764. if (this.uvs6) {
  31765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31766. }
  31767. if (this.colors) {
  31768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31769. }
  31770. if (this.matricesIndices) {
  31771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31772. }
  31773. if (this.matricesWeights) {
  31774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31775. }
  31776. if (this.matricesIndicesExtra) {
  31777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31778. }
  31779. if (this.matricesWeightsExtra) {
  31780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31781. }
  31782. if (this.indices) {
  31783. meshOrGeometry.setIndices(this.indices, null);
  31784. }
  31785. return this;
  31786. };
  31787. /**
  31788. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31789. * Returns the VertexData.
  31790. */
  31791. VertexData.prototype.transform = function (matrix) {
  31792. var transformed = BABYLON.Vector3.Zero();
  31793. var index;
  31794. if (this.positions) {
  31795. var position = BABYLON.Vector3.Zero();
  31796. for (index = 0; index < this.positions.length; index += 3) {
  31797. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31798. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31799. this.positions[index] = transformed.x;
  31800. this.positions[index + 1] = transformed.y;
  31801. this.positions[index + 2] = transformed.z;
  31802. }
  31803. }
  31804. if (this.normals) {
  31805. var normal = BABYLON.Vector3.Zero();
  31806. for (index = 0; index < this.normals.length; index += 3) {
  31807. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31808. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31809. this.normals[index] = transformed.x;
  31810. this.normals[index + 1] = transformed.y;
  31811. this.normals[index + 2] = transformed.z;
  31812. }
  31813. }
  31814. if (this.tangents) {
  31815. var tangent = BABYLON.Vector4.Zero();
  31816. var tangentTransformed = BABYLON.Vector4.Zero();
  31817. for (index = 0; index < this.tangents.length; index += 4) {
  31818. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31819. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31820. this.tangents[index] = tangentTransformed.x;
  31821. this.tangents[index + 1] = tangentTransformed.y;
  31822. this.tangents[index + 2] = tangentTransformed.z;
  31823. this.tangents[index + 3] = tangentTransformed.w;
  31824. }
  31825. }
  31826. return this;
  31827. };
  31828. /**
  31829. * Merges the passed VertexData into the current one.
  31830. * Returns the modified VertexData.
  31831. */
  31832. VertexData.prototype.merge = function (other) {
  31833. this._validate();
  31834. other._validate();
  31835. if (!this.normals !== !other.normals ||
  31836. !this.tangents !== !other.tangents ||
  31837. !this.uvs !== !other.uvs ||
  31838. !this.uvs2 !== !other.uvs2 ||
  31839. !this.uvs3 !== !other.uvs3 ||
  31840. !this.uvs4 !== !other.uvs4 ||
  31841. !this.uvs5 !== !other.uvs5 ||
  31842. !this.uvs6 !== !other.uvs6 ||
  31843. !this.colors !== !other.colors ||
  31844. !this.matricesIndices !== !other.matricesIndices ||
  31845. !this.matricesWeights !== !other.matricesWeights ||
  31846. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31847. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31848. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31849. }
  31850. if (other.indices) {
  31851. if (!this.indices) {
  31852. this.indices = [];
  31853. }
  31854. var offset = this.positions ? this.positions.length / 3 : 0;
  31855. for (var index = 0; index < other.indices.length; index++) {
  31856. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31857. this.indices.push(other.indices[index] + offset);
  31858. }
  31859. }
  31860. this.positions = this._mergeElement(this.positions, other.positions);
  31861. this.normals = this._mergeElement(this.normals, other.normals);
  31862. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31863. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31864. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31865. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31866. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31867. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31868. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31869. this.colors = this._mergeElement(this.colors, other.colors);
  31870. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31871. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31872. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31873. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31874. return this;
  31875. };
  31876. VertexData.prototype._mergeElement = function (source, other) {
  31877. if (!source) {
  31878. return other;
  31879. }
  31880. if (!other) {
  31881. return source;
  31882. }
  31883. var len = other.length + source.length;
  31884. var isSrcTypedArray = source instanceof Float32Array;
  31885. var isOthTypedArray = other instanceof Float32Array;
  31886. // use non-loop method when the source is Float32Array
  31887. if (isSrcTypedArray) {
  31888. var ret32 = new Float32Array(len);
  31889. ret32.set(source);
  31890. ret32.set(other, source.length);
  31891. return ret32;
  31892. // source is number[], when other is also use concat
  31893. }
  31894. else if (!isOthTypedArray) {
  31895. return source.concat(other);
  31896. // source is a number[], but other is a Float32Array, loop required
  31897. }
  31898. else {
  31899. var ret = source.slice(0); // copy source to a separate array
  31900. for (var i = 0, len = other.length; i < len; i++) {
  31901. ret.push(other[i]);
  31902. }
  31903. return ret;
  31904. }
  31905. };
  31906. VertexData.prototype._validate = function () {
  31907. if (!this.positions) {
  31908. throw new Error("Positions are required");
  31909. }
  31910. var getElementCount = function (kind, values) {
  31911. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  31912. if ((values.length % stride) !== 0) {
  31913. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  31914. }
  31915. return values.length / stride;
  31916. };
  31917. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  31918. var validateElementCount = function (kind, values) {
  31919. var elementCount = getElementCount(kind, values);
  31920. if (elementCount !== positionsElementCount) {
  31921. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  31922. }
  31923. };
  31924. if (this.normals)
  31925. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  31926. if (this.tangents)
  31927. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  31928. if (this.uvs)
  31929. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  31930. if (this.uvs2)
  31931. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  31932. if (this.uvs3)
  31933. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  31934. if (this.uvs4)
  31935. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  31936. if (this.uvs5)
  31937. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  31938. if (this.uvs6)
  31939. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  31940. if (this.colors)
  31941. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  31942. if (this.matricesIndices)
  31943. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  31944. if (this.matricesWeights)
  31945. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  31946. if (this.matricesIndicesExtra)
  31947. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  31948. if (this.matricesWeightsExtra)
  31949. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  31950. };
  31951. /**
  31952. * Serializes the VertexData.
  31953. * Returns a serialized object.
  31954. */
  31955. VertexData.prototype.serialize = function () {
  31956. var serializationObject = this.serialize();
  31957. if (this.positions) {
  31958. serializationObject.positions = this.positions;
  31959. }
  31960. if (this.normals) {
  31961. serializationObject.normals = this.normals;
  31962. }
  31963. if (this.tangents) {
  31964. serializationObject.tangents = this.tangents;
  31965. }
  31966. if (this.uvs) {
  31967. serializationObject.uvs = this.uvs;
  31968. }
  31969. if (this.uvs2) {
  31970. serializationObject.uvs2 = this.uvs2;
  31971. }
  31972. if (this.uvs3) {
  31973. serializationObject.uvs3 = this.uvs3;
  31974. }
  31975. if (this.uvs4) {
  31976. serializationObject.uvs4 = this.uvs4;
  31977. }
  31978. if (this.uvs5) {
  31979. serializationObject.uvs5 = this.uvs5;
  31980. }
  31981. if (this.uvs6) {
  31982. serializationObject.uvs6 = this.uvs6;
  31983. }
  31984. if (this.colors) {
  31985. serializationObject.colors = this.colors;
  31986. }
  31987. if (this.matricesIndices) {
  31988. serializationObject.matricesIndices = this.matricesIndices;
  31989. serializationObject.matricesIndices._isExpanded = true;
  31990. }
  31991. if (this.matricesWeights) {
  31992. serializationObject.matricesWeights = this.matricesWeights;
  31993. }
  31994. if (this.matricesIndicesExtra) {
  31995. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31996. serializationObject.matricesIndicesExtra._isExpanded = true;
  31997. }
  31998. if (this.matricesWeightsExtra) {
  31999. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32000. }
  32001. serializationObject.indices = this.indices;
  32002. return serializationObject;
  32003. };
  32004. // Statics
  32005. /**
  32006. * Returns the object VertexData associated to the passed mesh.
  32007. */
  32008. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32009. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32010. };
  32011. /**
  32012. * Returns the object VertexData associated to the passed geometry.
  32013. */
  32014. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32015. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32016. };
  32017. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32018. var result = new VertexData();
  32019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32020. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32021. }
  32022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32023. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32024. }
  32025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32026. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32027. }
  32028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32029. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32030. }
  32031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32032. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32033. }
  32034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32035. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32036. }
  32037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32038. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32039. }
  32040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32041. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32042. }
  32043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32044. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32045. }
  32046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32047. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32048. }
  32049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32050. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32051. }
  32052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32053. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32054. }
  32055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32056. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32057. }
  32058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32059. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32060. }
  32061. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32062. return result;
  32063. };
  32064. /**
  32065. * Creates the vertexData of the Ribbon.
  32066. */
  32067. VertexData.CreateRibbon = function (options) {
  32068. var pathArray = options.pathArray;
  32069. var closeArray = options.closeArray || false;
  32070. var closePath = options.closePath || false;
  32071. var invertUV = options.invertUV || false;
  32072. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32073. var offset = options.offset || defaultOffset;
  32074. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32075. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32076. var customUV = options.uvs;
  32077. var customColors = options.colors;
  32078. var positions = [];
  32079. var indices = [];
  32080. var normals = [];
  32081. var uvs = [];
  32082. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32083. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32084. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32085. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32086. var minlg; // minimal length among all paths from pathArray
  32087. var lg = []; // array of path lengths : nb of vertex per path
  32088. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32089. var p; // path iterator
  32090. var i; // point iterator
  32091. var j; // point iterator
  32092. // if single path in pathArray
  32093. if (pathArray.length < 2) {
  32094. var ar1 = [];
  32095. var ar2 = [];
  32096. for (i = 0; i < pathArray[0].length - offset; i++) {
  32097. ar1.push(pathArray[0][i]);
  32098. ar2.push(pathArray[0][i + offset]);
  32099. }
  32100. pathArray = [ar1, ar2];
  32101. }
  32102. // positions and horizontal distances (u)
  32103. var idc = 0;
  32104. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32105. var path;
  32106. var l;
  32107. minlg = pathArray[0].length;
  32108. var vectlg;
  32109. var dist;
  32110. for (p = 0; p < pathArray.length; p++) {
  32111. uTotalDistance[p] = 0;
  32112. us[p] = [0];
  32113. path = pathArray[p];
  32114. l = path.length;
  32115. minlg = (minlg < l) ? minlg : l;
  32116. j = 0;
  32117. while (j < l) {
  32118. positions.push(path[j].x, path[j].y, path[j].z);
  32119. if (j > 0) {
  32120. vectlg = path[j].subtract(path[j - 1]).length();
  32121. dist = vectlg + uTotalDistance[p];
  32122. us[p].push(dist);
  32123. uTotalDistance[p] = dist;
  32124. }
  32125. j++;
  32126. }
  32127. if (closePath) {
  32128. j--;
  32129. positions.push(path[0].x, path[0].y, path[0].z);
  32130. vectlg = path[j].subtract(path[0]).length();
  32131. dist = vectlg + uTotalDistance[p];
  32132. us[p].push(dist);
  32133. uTotalDistance[p] = dist;
  32134. }
  32135. lg[p] = l + closePathCorr;
  32136. idx[p] = idc;
  32137. idc += (l + closePathCorr);
  32138. }
  32139. // vertical distances (v)
  32140. var path1;
  32141. var path2;
  32142. var vertex1 = null;
  32143. var vertex2 = null;
  32144. for (i = 0; i < minlg + closePathCorr; i++) {
  32145. vTotalDistance[i] = 0;
  32146. vs[i] = [0];
  32147. for (p = 0; p < pathArray.length - 1; p++) {
  32148. path1 = pathArray[p];
  32149. path2 = pathArray[p + 1];
  32150. if (i === minlg) {
  32151. vertex1 = path1[0];
  32152. vertex2 = path2[0];
  32153. }
  32154. else {
  32155. vertex1 = path1[i];
  32156. vertex2 = path2[i];
  32157. }
  32158. vectlg = vertex2.subtract(vertex1).length();
  32159. dist = vectlg + vTotalDistance[i];
  32160. vs[i].push(dist);
  32161. vTotalDistance[i] = dist;
  32162. }
  32163. if (closeArray && vertex2 && vertex1) {
  32164. path1 = pathArray[p];
  32165. path2 = pathArray[0];
  32166. if (i === minlg) {
  32167. vertex2 = path2[0];
  32168. }
  32169. vectlg = vertex2.subtract(vertex1).length();
  32170. dist = vectlg + vTotalDistance[i];
  32171. vTotalDistance[i] = dist;
  32172. }
  32173. }
  32174. // uvs
  32175. var u;
  32176. var v;
  32177. if (customUV) {
  32178. for (p = 0; p < customUV.length; p++) {
  32179. uvs.push(customUV[p].x, customUV[p].y);
  32180. }
  32181. }
  32182. else {
  32183. for (p = 0; p < pathArray.length; p++) {
  32184. for (i = 0; i < minlg + closePathCorr; i++) {
  32185. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32186. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32187. if (invertUV) {
  32188. uvs.push(v, u);
  32189. }
  32190. else {
  32191. uvs.push(u, v);
  32192. }
  32193. }
  32194. }
  32195. }
  32196. // indices
  32197. p = 0; // path index
  32198. var pi = 0; // positions array index
  32199. var l1 = lg[p] - 1; // path1 length
  32200. var l2 = lg[p + 1] - 1; // path2 length
  32201. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32202. var shft = idx[1] - idx[0]; // shift
  32203. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32204. while (pi <= min && p < path1nb) {
  32205. // 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
  32206. indices.push(pi, pi + shft, pi + 1);
  32207. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32208. pi += 1;
  32209. if (pi === min) {
  32210. p++;
  32211. if (p === lg.length - 1) {
  32212. shft = idx[0] - idx[p];
  32213. l1 = lg[p] - 1;
  32214. l2 = lg[0] - 1;
  32215. }
  32216. else {
  32217. shft = idx[p + 1] - idx[p];
  32218. l1 = lg[p] - 1;
  32219. l2 = lg[p + 1] - 1;
  32220. }
  32221. pi = idx[p];
  32222. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32223. }
  32224. }
  32225. // normals
  32226. VertexData.ComputeNormals(positions, indices, normals);
  32227. if (closePath) {
  32228. var indexFirst = 0;
  32229. var indexLast = 0;
  32230. for (p = 0; p < pathArray.length; p++) {
  32231. indexFirst = idx[p] * 3;
  32232. if (p + 1 < pathArray.length) {
  32233. indexLast = (idx[p + 1] - 1) * 3;
  32234. }
  32235. else {
  32236. indexLast = normals.length - 3;
  32237. }
  32238. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32239. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32240. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32241. normals[indexLast] = normals[indexFirst];
  32242. normals[indexLast + 1] = normals[indexFirst + 1];
  32243. normals[indexLast + 2] = normals[indexFirst + 2];
  32244. }
  32245. }
  32246. // sides
  32247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32248. // Colors
  32249. var colors = null;
  32250. if (customColors) {
  32251. colors = new Float32Array(customColors.length * 4);
  32252. for (var c = 0; c < customColors.length; c++) {
  32253. colors[c * 4] = customColors[c].r;
  32254. colors[c * 4 + 1] = customColors[c].g;
  32255. colors[c * 4 + 2] = customColors[c].b;
  32256. colors[c * 4 + 3] = customColors[c].a;
  32257. }
  32258. }
  32259. // Result
  32260. var vertexData = new VertexData();
  32261. var positions32 = new Float32Array(positions);
  32262. var normals32 = new Float32Array(normals);
  32263. var uvs32 = new Float32Array(uvs);
  32264. vertexData.indices = indices;
  32265. vertexData.positions = positions32;
  32266. vertexData.normals = normals32;
  32267. vertexData.uvs = uvs32;
  32268. if (colors) {
  32269. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32270. }
  32271. if (closePath) {
  32272. vertexData._idx = idx;
  32273. }
  32274. return vertexData;
  32275. };
  32276. /**
  32277. * Creates the VertexData of the Box.
  32278. */
  32279. VertexData.CreateBox = function (options) {
  32280. var normalsSource = [
  32281. new BABYLON.Vector3(0, 0, 1),
  32282. new BABYLON.Vector3(0, 0, -1),
  32283. new BABYLON.Vector3(1, 0, 0),
  32284. new BABYLON.Vector3(-1, 0, 0),
  32285. new BABYLON.Vector3(0, 1, 0),
  32286. new BABYLON.Vector3(0, -1, 0)
  32287. ];
  32288. var indices = [];
  32289. var positions = [];
  32290. var normals = [];
  32291. var uvs = [];
  32292. var width = options.width || options.size || 1;
  32293. var height = options.height || options.size || 1;
  32294. var depth = options.depth || options.size || 1;
  32295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32296. var faceUV = options.faceUV || new Array(6);
  32297. var faceColors = options.faceColors;
  32298. var colors = [];
  32299. // default face colors and UV if undefined
  32300. for (var f = 0; f < 6; f++) {
  32301. if (faceUV[f] === undefined) {
  32302. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32303. }
  32304. if (faceColors && faceColors[f] === undefined) {
  32305. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32306. }
  32307. }
  32308. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32309. // Create each face in turn.
  32310. for (var index = 0; index < normalsSource.length; index++) {
  32311. var normal = normalsSource[index];
  32312. // Get two vectors perpendicular to the face normal and to each other.
  32313. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32314. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32315. // Six indices (two triangles) per face.
  32316. var verticesLength = positions.length / 3;
  32317. indices.push(verticesLength);
  32318. indices.push(verticesLength + 1);
  32319. indices.push(verticesLength + 2);
  32320. indices.push(verticesLength);
  32321. indices.push(verticesLength + 2);
  32322. indices.push(verticesLength + 3);
  32323. // Four vertices per face.
  32324. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32325. positions.push(vertex.x, vertex.y, vertex.z);
  32326. normals.push(normal.x, normal.y, normal.z);
  32327. uvs.push(faceUV[index].z, faceUV[index].w);
  32328. if (faceColors) {
  32329. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32330. }
  32331. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32332. positions.push(vertex.x, vertex.y, vertex.z);
  32333. normals.push(normal.x, normal.y, normal.z);
  32334. uvs.push(faceUV[index].x, faceUV[index].w);
  32335. if (faceColors) {
  32336. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32337. }
  32338. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32339. positions.push(vertex.x, vertex.y, vertex.z);
  32340. normals.push(normal.x, normal.y, normal.z);
  32341. uvs.push(faceUV[index].x, faceUV[index].y);
  32342. if (faceColors) {
  32343. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32344. }
  32345. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32346. positions.push(vertex.x, vertex.y, vertex.z);
  32347. normals.push(normal.x, normal.y, normal.z);
  32348. uvs.push(faceUV[index].z, faceUV[index].y);
  32349. if (faceColors) {
  32350. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32351. }
  32352. }
  32353. // sides
  32354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32355. // Result
  32356. var vertexData = new VertexData();
  32357. vertexData.indices = indices;
  32358. vertexData.positions = positions;
  32359. vertexData.normals = normals;
  32360. vertexData.uvs = uvs;
  32361. if (faceColors) {
  32362. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32363. vertexData.colors = totalColors;
  32364. }
  32365. return vertexData;
  32366. };
  32367. /**
  32368. * Creates the VertexData of the Sphere.
  32369. */
  32370. VertexData.CreateSphere = function (options) {
  32371. var segments = options.segments || 32;
  32372. var diameterX = options.diameterX || options.diameter || 1;
  32373. var diameterY = options.diameterY || options.diameter || 1;
  32374. var diameterZ = options.diameterZ || options.diameter || 1;
  32375. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32376. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32377. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32378. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32379. var totalZRotationSteps = 2 + segments;
  32380. var totalYRotationSteps = 2 * totalZRotationSteps;
  32381. var indices = [];
  32382. var positions = [];
  32383. var normals = [];
  32384. var uvs = [];
  32385. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32386. var normalizedZ = zRotationStep / totalZRotationSteps;
  32387. var angleZ = normalizedZ * Math.PI * slice;
  32388. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32389. var normalizedY = yRotationStep / totalYRotationSteps;
  32390. var angleY = normalizedY * Math.PI * 2 * arc;
  32391. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32392. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32393. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32394. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32395. var vertex = complete.multiply(radius);
  32396. var normal = complete.divide(radius).normalize();
  32397. positions.push(vertex.x, vertex.y, vertex.z);
  32398. normals.push(normal.x, normal.y, normal.z);
  32399. uvs.push(normalizedY, normalizedZ);
  32400. }
  32401. if (zRotationStep > 0) {
  32402. var verticesCount = positions.length / 3;
  32403. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32404. indices.push((firstIndex));
  32405. indices.push((firstIndex + 1));
  32406. indices.push(firstIndex + totalYRotationSteps + 1);
  32407. indices.push((firstIndex + totalYRotationSteps + 1));
  32408. indices.push((firstIndex + 1));
  32409. indices.push((firstIndex + totalYRotationSteps + 2));
  32410. }
  32411. }
  32412. }
  32413. // Sides
  32414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32415. // Result
  32416. var vertexData = new VertexData();
  32417. vertexData.indices = indices;
  32418. vertexData.positions = positions;
  32419. vertexData.normals = normals;
  32420. vertexData.uvs = uvs;
  32421. return vertexData;
  32422. };
  32423. /**
  32424. * Creates the VertexData of the Cylinder or Cone.
  32425. */
  32426. VertexData.CreateCylinder = function (options) {
  32427. var height = options.height || 2;
  32428. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32429. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32430. var tessellation = options.tessellation || 24;
  32431. var subdivisions = options.subdivisions || 1;
  32432. var hasRings = options.hasRings ? true : false;
  32433. var enclose = options.enclose ? true : false;
  32434. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32435. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32436. var faceUV = options.faceUV || new Array(3);
  32437. var faceColors = options.faceColors;
  32438. // default face colors and UV if undefined
  32439. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32440. var ringNb = (hasRings) ? subdivisions : 1;
  32441. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32442. var f;
  32443. for (f = 0; f < surfaceNb; f++) {
  32444. if (faceColors && faceColors[f] === undefined) {
  32445. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32446. }
  32447. }
  32448. for (f = 0; f < surfaceNb; f++) {
  32449. if (faceUV && faceUV[f] === undefined) {
  32450. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32451. }
  32452. }
  32453. var indices = new Array();
  32454. var positions = new Array();
  32455. var normals = new Array();
  32456. var uvs = new Array();
  32457. var colors = new Array();
  32458. var angle_step = Math.PI * 2 * arc / tessellation;
  32459. var angle;
  32460. var h;
  32461. var radius;
  32462. var tan = (diameterBottom - diameterTop) / 2 / height;
  32463. var ringVertex = BABYLON.Vector3.Zero();
  32464. var ringNormal = BABYLON.Vector3.Zero();
  32465. var ringFirstVertex = BABYLON.Vector3.Zero();
  32466. var ringFirstNormal = BABYLON.Vector3.Zero();
  32467. var quadNormal = BABYLON.Vector3.Zero();
  32468. var Y = BABYLON.Axis.Y;
  32469. // positions, normals, uvs
  32470. var i;
  32471. var j;
  32472. var r;
  32473. var ringIdx = 1;
  32474. var s = 1; // surface index
  32475. var cs = 0;
  32476. var v = 0;
  32477. for (i = 0; i <= subdivisions; i++) {
  32478. h = i / subdivisions;
  32479. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32480. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32481. for (r = 0; r < ringIdx; r++) {
  32482. if (hasRings) {
  32483. s += r;
  32484. }
  32485. if (enclose) {
  32486. s += 2 * r;
  32487. }
  32488. for (j = 0; j <= tessellation; j++) {
  32489. angle = j * angle_step;
  32490. // position
  32491. ringVertex.x = Math.cos(-angle) * radius;
  32492. ringVertex.y = -height / 2 + h * height;
  32493. ringVertex.z = Math.sin(-angle) * radius;
  32494. // normal
  32495. if (diameterTop === 0 && i === subdivisions) {
  32496. // if no top cap, reuse former normals
  32497. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32498. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32499. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32500. }
  32501. else {
  32502. ringNormal.x = ringVertex.x;
  32503. ringNormal.z = ringVertex.z;
  32504. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32505. ringNormal.normalize();
  32506. }
  32507. // keep first ring vertex values for enclose
  32508. if (j === 0) {
  32509. ringFirstVertex.copyFrom(ringVertex);
  32510. ringFirstNormal.copyFrom(ringNormal);
  32511. }
  32512. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32513. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32514. if (hasRings) {
  32515. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32516. }
  32517. else {
  32518. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32519. }
  32520. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32521. if (faceColors) {
  32522. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32523. }
  32524. }
  32525. // if enclose, add four vertices and their dedicated normals
  32526. if (arc !== 1 && enclose) {
  32527. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32528. positions.push(0, ringVertex.y, 0);
  32529. positions.push(0, ringVertex.y, 0);
  32530. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32531. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32532. quadNormal.normalize();
  32533. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32534. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32535. quadNormal.normalize();
  32536. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32537. if (hasRings) {
  32538. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32539. }
  32540. else {
  32541. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32542. }
  32543. uvs.push(faceUV[s + 1].x, v);
  32544. uvs.push(faceUV[s + 1].z, v);
  32545. if (hasRings) {
  32546. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32547. }
  32548. else {
  32549. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32550. }
  32551. uvs.push(faceUV[s + 2].x, v);
  32552. uvs.push(faceUV[s + 2].z, v);
  32553. if (faceColors) {
  32554. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32555. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32556. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32557. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32558. }
  32559. }
  32560. if (cs !== s) {
  32561. cs = s;
  32562. }
  32563. }
  32564. }
  32565. // indices
  32566. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32567. var s;
  32568. i = 0;
  32569. for (s = 0; s < subdivisions; s++) {
  32570. var i0 = 0;
  32571. var i1 = 0;
  32572. var i2 = 0;
  32573. var i3 = 0;
  32574. for (j = 0; j < tessellation; j++) {
  32575. i0 = i * (e + 1) + j;
  32576. i1 = (i + 1) * (e + 1) + j;
  32577. i2 = i * (e + 1) + (j + 1);
  32578. i3 = (i + 1) * (e + 1) + (j + 1);
  32579. indices.push(i0, i1, i2);
  32580. indices.push(i3, i2, i1);
  32581. }
  32582. if (arc !== 1 && enclose) {
  32583. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32584. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32585. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32586. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32587. }
  32588. i = (hasRings) ? (i + 2) : (i + 1);
  32589. }
  32590. // Caps
  32591. var createCylinderCap = function (isTop) {
  32592. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32593. if (radius === 0) {
  32594. return;
  32595. }
  32596. // Cap positions, normals & uvs
  32597. var angle;
  32598. var circleVector;
  32599. var i;
  32600. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32601. var c = null;
  32602. if (faceColors) {
  32603. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32604. }
  32605. // cap center
  32606. var vbase = positions.length / 3;
  32607. var offset = isTop ? height / 2 : -height / 2;
  32608. var center = new BABYLON.Vector3(0, offset, 0);
  32609. positions.push(center.x, center.y, center.z);
  32610. normals.push(0, isTop ? 1 : -1, 0);
  32611. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32612. if (c) {
  32613. colors.push(c.r, c.g, c.b, c.a);
  32614. }
  32615. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32616. for (i = 0; i <= tessellation; i++) {
  32617. angle = Math.PI * 2 * i * arc / tessellation;
  32618. var cos = Math.cos(-angle);
  32619. var sin = Math.sin(-angle);
  32620. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32621. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32622. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32623. normals.push(0, isTop ? 1 : -1, 0);
  32624. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32625. if (c) {
  32626. colors.push(c.r, c.g, c.b, c.a);
  32627. }
  32628. }
  32629. // Cap indices
  32630. for (i = 0; i < tessellation; i++) {
  32631. if (!isTop) {
  32632. indices.push(vbase);
  32633. indices.push(vbase + (i + 1));
  32634. indices.push(vbase + (i + 2));
  32635. }
  32636. else {
  32637. indices.push(vbase);
  32638. indices.push(vbase + (i + 2));
  32639. indices.push(vbase + (i + 1));
  32640. }
  32641. }
  32642. };
  32643. // add caps to geometry
  32644. createCylinderCap(false);
  32645. createCylinderCap(true);
  32646. // Sides
  32647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32648. var vertexData = new VertexData();
  32649. vertexData.indices = indices;
  32650. vertexData.positions = positions;
  32651. vertexData.normals = normals;
  32652. vertexData.uvs = uvs;
  32653. if (faceColors) {
  32654. vertexData.colors = colors;
  32655. }
  32656. return vertexData;
  32657. };
  32658. /**
  32659. * Creates the VertexData of the Torus.
  32660. */
  32661. VertexData.CreateTorus = function (options) {
  32662. var indices = [];
  32663. var positions = [];
  32664. var normals = [];
  32665. var uvs = [];
  32666. var diameter = options.diameter || 1;
  32667. var thickness = options.thickness || 0.5;
  32668. var tessellation = options.tessellation || 16;
  32669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32670. var stride = tessellation + 1;
  32671. for (var i = 0; i <= tessellation; i++) {
  32672. var u = i / tessellation;
  32673. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32674. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32675. for (var j = 0; j <= tessellation; j++) {
  32676. var v = 1 - j / tessellation;
  32677. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32678. var dx = Math.cos(innerAngle);
  32679. var dy = Math.sin(innerAngle);
  32680. // Create a vertex.
  32681. var normal = new BABYLON.Vector3(dx, dy, 0);
  32682. var position = normal.scale(thickness / 2);
  32683. var textureCoordinate = new BABYLON.Vector2(u, v);
  32684. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32685. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32686. positions.push(position.x, position.y, position.z);
  32687. normals.push(normal.x, normal.y, normal.z);
  32688. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32689. // And create indices for two triangles.
  32690. var nextI = (i + 1) % stride;
  32691. var nextJ = (j + 1) % stride;
  32692. indices.push(i * stride + j);
  32693. indices.push(i * stride + nextJ);
  32694. indices.push(nextI * stride + j);
  32695. indices.push(i * stride + nextJ);
  32696. indices.push(nextI * stride + nextJ);
  32697. indices.push(nextI * stride + j);
  32698. }
  32699. }
  32700. // Sides
  32701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32702. // Result
  32703. var vertexData = new VertexData();
  32704. vertexData.indices = indices;
  32705. vertexData.positions = positions;
  32706. vertexData.normals = normals;
  32707. vertexData.uvs = uvs;
  32708. return vertexData;
  32709. };
  32710. /**
  32711. * Creates the VertexData of the LineSystem.
  32712. */
  32713. VertexData.CreateLineSystem = function (options) {
  32714. var indices = [];
  32715. var positions = [];
  32716. var lines = options.lines;
  32717. var colors = options.colors;
  32718. var vertexColors = [];
  32719. var idx = 0;
  32720. for (var l = 0; l < lines.length; l++) {
  32721. var points = lines[l];
  32722. for (var index = 0; index < points.length; index++) {
  32723. positions.push(points[index].x, points[index].y, points[index].z);
  32724. if (colors) {
  32725. var color = colors[l];
  32726. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32727. }
  32728. if (index > 0) {
  32729. indices.push(idx - 1);
  32730. indices.push(idx);
  32731. }
  32732. idx++;
  32733. }
  32734. }
  32735. var vertexData = new VertexData();
  32736. vertexData.indices = indices;
  32737. vertexData.positions = positions;
  32738. if (colors) {
  32739. vertexData.colors = vertexColors;
  32740. }
  32741. return vertexData;
  32742. };
  32743. /**
  32744. * Create the VertexData of the DashedLines.
  32745. */
  32746. VertexData.CreateDashedLines = function (options) {
  32747. var dashSize = options.dashSize || 3;
  32748. var gapSize = options.gapSize || 1;
  32749. var dashNb = options.dashNb || 200;
  32750. var points = options.points;
  32751. var positions = new Array();
  32752. var indices = new Array();
  32753. var curvect = BABYLON.Vector3.Zero();
  32754. var lg = 0;
  32755. var nb = 0;
  32756. var shft = 0;
  32757. var dashshft = 0;
  32758. var curshft = 0;
  32759. var idx = 0;
  32760. var i = 0;
  32761. for (i = 0; i < points.length - 1; i++) {
  32762. points[i + 1].subtractToRef(points[i], curvect);
  32763. lg += curvect.length();
  32764. }
  32765. shft = lg / dashNb;
  32766. dashshft = dashSize * shft / (dashSize + gapSize);
  32767. for (i = 0; i < points.length - 1; i++) {
  32768. points[i + 1].subtractToRef(points[i], curvect);
  32769. nb = Math.floor(curvect.length() / shft);
  32770. curvect.normalize();
  32771. for (var j = 0; j < nb; j++) {
  32772. curshft = shft * j;
  32773. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32774. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32775. indices.push(idx, idx + 1);
  32776. idx += 2;
  32777. }
  32778. }
  32779. // Result
  32780. var vertexData = new VertexData();
  32781. vertexData.positions = positions;
  32782. vertexData.indices = indices;
  32783. return vertexData;
  32784. };
  32785. /**
  32786. * Creates the VertexData of the Ground.
  32787. */
  32788. VertexData.CreateGround = function (options) {
  32789. var indices = [];
  32790. var positions = [];
  32791. var normals = [];
  32792. var uvs = [];
  32793. var row, col;
  32794. var width = options.width || 1;
  32795. var height = options.height || 1;
  32796. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32797. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32798. for (row = 0; row <= subdivisionsY; row++) {
  32799. for (col = 0; col <= subdivisionsX; col++) {
  32800. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32801. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32802. positions.push(position.x, position.y, position.z);
  32803. normals.push(normal.x, normal.y, normal.z);
  32804. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32805. }
  32806. }
  32807. for (row = 0; row < subdivisionsY; row++) {
  32808. for (col = 0; col < subdivisionsX; col++) {
  32809. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32810. indices.push(col + 1 + row * (subdivisionsX + 1));
  32811. indices.push(col + row * (subdivisionsX + 1));
  32812. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32813. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32814. indices.push(col + row * (subdivisionsX + 1));
  32815. }
  32816. }
  32817. // Result
  32818. var vertexData = new VertexData();
  32819. vertexData.indices = indices;
  32820. vertexData.positions = positions;
  32821. vertexData.normals = normals;
  32822. vertexData.uvs = uvs;
  32823. return vertexData;
  32824. };
  32825. /**
  32826. * Creates the VertexData of the TiledGround.
  32827. */
  32828. VertexData.CreateTiledGround = function (options) {
  32829. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32830. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32831. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32832. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32833. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32834. var precision = options.precision || { w: 1, h: 1 };
  32835. var indices = new Array();
  32836. var positions = new Array();
  32837. var normals = new Array();
  32838. var uvs = new Array();
  32839. var row, col, tileRow, tileCol;
  32840. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32841. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32842. precision.w = (precision.w < 1) ? 1 : precision.w;
  32843. precision.h = (precision.h < 1) ? 1 : precision.h;
  32844. var tileSize = {
  32845. 'w': (xmax - xmin) / subdivisions.w,
  32846. 'h': (zmax - zmin) / subdivisions.h
  32847. };
  32848. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32849. // Indices
  32850. var base = positions.length / 3;
  32851. var rowLength = precision.w + 1;
  32852. for (row = 0; row < precision.h; row++) {
  32853. for (col = 0; col < precision.w; col++) {
  32854. var square = [
  32855. base + col + row * rowLength,
  32856. base + (col + 1) + row * rowLength,
  32857. base + (col + 1) + (row + 1) * rowLength,
  32858. base + col + (row + 1) * rowLength
  32859. ];
  32860. indices.push(square[1]);
  32861. indices.push(square[2]);
  32862. indices.push(square[3]);
  32863. indices.push(square[0]);
  32864. indices.push(square[1]);
  32865. indices.push(square[3]);
  32866. }
  32867. }
  32868. // Position, normals and uvs
  32869. var position = BABYLON.Vector3.Zero();
  32870. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32871. for (row = 0; row <= precision.h; row++) {
  32872. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32873. for (col = 0; col <= precision.w; col++) {
  32874. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32875. position.y = 0;
  32876. positions.push(position.x, position.y, position.z);
  32877. normals.push(normal.x, normal.y, normal.z);
  32878. uvs.push(col / precision.w, row / precision.h);
  32879. }
  32880. }
  32881. }
  32882. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32883. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32884. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32885. }
  32886. }
  32887. // Result
  32888. var vertexData = new VertexData();
  32889. vertexData.indices = indices;
  32890. vertexData.positions = positions;
  32891. vertexData.normals = normals;
  32892. vertexData.uvs = uvs;
  32893. return vertexData;
  32894. };
  32895. /**
  32896. * Creates the VertexData of the Ground designed from a heightmap.
  32897. */
  32898. VertexData.CreateGroundFromHeightMap = function (options) {
  32899. var indices = [];
  32900. var positions = [];
  32901. var normals = [];
  32902. var uvs = [];
  32903. var row, col;
  32904. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  32905. // Vertices
  32906. for (row = 0; row <= options.subdivisions; row++) {
  32907. for (col = 0; col <= options.subdivisions; col++) {
  32908. 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));
  32909. // Compute height
  32910. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32911. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32912. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32913. var r = options.buffer[pos] / 255.0;
  32914. var g = options.buffer[pos + 1] / 255.0;
  32915. var b = options.buffer[pos + 2] / 255.0;
  32916. var gradient = r * filter.r + g * filter.g + b * filter.b;
  32917. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32918. // Add vertex
  32919. positions.push(position.x, position.y, position.z);
  32920. normals.push(0, 0, 0);
  32921. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32922. }
  32923. }
  32924. // Indices
  32925. for (row = 0; row < options.subdivisions; row++) {
  32926. for (col = 0; col < options.subdivisions; col++) {
  32927. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32928. indices.push(col + 1 + row * (options.subdivisions + 1));
  32929. indices.push(col + row * (options.subdivisions + 1));
  32930. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32931. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32932. indices.push(col + row * (options.subdivisions + 1));
  32933. }
  32934. }
  32935. // Normals
  32936. VertexData.ComputeNormals(positions, indices, normals);
  32937. // Result
  32938. var vertexData = new VertexData();
  32939. vertexData.indices = indices;
  32940. vertexData.positions = positions;
  32941. vertexData.normals = normals;
  32942. vertexData.uvs = uvs;
  32943. return vertexData;
  32944. };
  32945. /**
  32946. * Creates the VertexData of the Plane.
  32947. */
  32948. VertexData.CreatePlane = function (options) {
  32949. var indices = [];
  32950. var positions = [];
  32951. var normals = [];
  32952. var uvs = [];
  32953. var width = options.width || options.size || 1;
  32954. var height = options.height || options.size || 1;
  32955. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32956. // Vertices
  32957. var halfWidth = width / 2.0;
  32958. var halfHeight = height / 2.0;
  32959. positions.push(-halfWidth, -halfHeight, 0);
  32960. normals.push(0, 0, -1.0);
  32961. uvs.push(0.0, 0.0);
  32962. positions.push(halfWidth, -halfHeight, 0);
  32963. normals.push(0, 0, -1.0);
  32964. uvs.push(1.0, 0.0);
  32965. positions.push(halfWidth, halfHeight, 0);
  32966. normals.push(0, 0, -1.0);
  32967. uvs.push(1.0, 1.0);
  32968. positions.push(-halfWidth, halfHeight, 0);
  32969. normals.push(0, 0, -1.0);
  32970. uvs.push(0.0, 1.0);
  32971. // Indices
  32972. indices.push(0);
  32973. indices.push(1);
  32974. indices.push(2);
  32975. indices.push(0);
  32976. indices.push(2);
  32977. indices.push(3);
  32978. // Sides
  32979. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32980. // Result
  32981. var vertexData = new VertexData();
  32982. vertexData.indices = indices;
  32983. vertexData.positions = positions;
  32984. vertexData.normals = normals;
  32985. vertexData.uvs = uvs;
  32986. return vertexData;
  32987. };
  32988. /**
  32989. * Creates the VertexData of the Disc or regular Polygon.
  32990. */
  32991. VertexData.CreateDisc = function (options) {
  32992. var positions = new Array();
  32993. var indices = new Array();
  32994. var normals = new Array();
  32995. var uvs = new Array();
  32996. var radius = options.radius || 0.5;
  32997. var tessellation = options.tessellation || 64;
  32998. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32999. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33000. // positions and uvs
  33001. positions.push(0, 0, 0); // disc center first
  33002. uvs.push(0.5, 0.5);
  33003. var theta = Math.PI * 2 * arc;
  33004. var step = theta / tessellation;
  33005. for (var a = 0; a < theta; a += step) {
  33006. var x = Math.cos(a);
  33007. var y = Math.sin(a);
  33008. var u = (x + 1) / 2;
  33009. var v = (1 - y) / 2;
  33010. positions.push(radius * x, radius * y, 0);
  33011. uvs.push(u, v);
  33012. }
  33013. if (arc === 1) {
  33014. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33015. uvs.push(uvs[2], uvs[3]);
  33016. }
  33017. //indices
  33018. var vertexNb = positions.length / 3;
  33019. for (var i = 1; i < vertexNb - 1; i++) {
  33020. indices.push(i + 1, 0, i);
  33021. }
  33022. // result
  33023. VertexData.ComputeNormals(positions, indices, normals);
  33024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33025. var vertexData = new VertexData();
  33026. vertexData.indices = indices;
  33027. vertexData.positions = positions;
  33028. vertexData.normals = normals;
  33029. vertexData.uvs = uvs;
  33030. return vertexData;
  33031. };
  33032. /**
  33033. * Re-creates the VertexData of the Polygon for sideOrientation.
  33034. */
  33035. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33036. var faceUV = fUV || new Array(3);
  33037. var faceColors = fColors;
  33038. var colors = [];
  33039. // default face colors and UV if undefined
  33040. for (var f = 0; f < 3; f++) {
  33041. if (faceUV[f] === undefined) {
  33042. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33043. }
  33044. if (faceColors && faceColors[f] === undefined) {
  33045. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33046. }
  33047. }
  33048. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33049. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33050. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33051. var indices = polygon.getIndices();
  33052. // set face colours and textures
  33053. var idx = 0;
  33054. var face = 0;
  33055. for (var index = 0; index < normals.length; index += 3) {
  33056. //Edge Face no. 1
  33057. if (Math.abs(normals[index + 1]) < 0.001) {
  33058. face = 1;
  33059. }
  33060. //Top Face no. 0
  33061. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33062. face = 0;
  33063. }
  33064. //Bottom Face no. 2
  33065. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33066. face = 2;
  33067. }
  33068. idx = index / 3;
  33069. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33070. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33071. if (faceColors) {
  33072. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33073. }
  33074. }
  33075. // sides
  33076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33077. // Result
  33078. var vertexData = new VertexData();
  33079. vertexData.indices = indices;
  33080. vertexData.positions = positions;
  33081. vertexData.normals = normals;
  33082. vertexData.uvs = uvs;
  33083. if (faceColors) {
  33084. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33085. vertexData.colors = totalColors;
  33086. }
  33087. return vertexData;
  33088. };
  33089. /**
  33090. * Creates the VertexData of the IcoSphere.
  33091. */
  33092. VertexData.CreateIcoSphere = function (options) {
  33093. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33094. var radius = options.radius || 1;
  33095. var flat = (options.flat === undefined) ? true : options.flat;
  33096. var subdivisions = options.subdivisions || 4;
  33097. var radiusX = options.radiusX || radius;
  33098. var radiusY = options.radiusY || radius;
  33099. var radiusZ = options.radiusZ || radius;
  33100. var t = (1 + Math.sqrt(5)) / 2;
  33101. // 12 vertex x,y,z
  33102. var ico_vertices = [
  33103. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33104. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33105. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33106. ];
  33107. // index of 3 vertex makes a face of icopshere
  33108. var ico_indices = [
  33109. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33110. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33111. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33112. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33113. ];
  33114. // vertex for uv have aliased position, not for UV
  33115. var vertices_unalias_id = [
  33116. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33117. // vertex alias
  33118. 0,
  33119. 2,
  33120. 3,
  33121. 3,
  33122. 3,
  33123. 4,
  33124. 7,
  33125. 8,
  33126. 9,
  33127. 9,
  33128. 10,
  33129. 11 // 23: B + 12
  33130. ];
  33131. // uv as integer step (not pixels !)
  33132. var ico_vertexuv = [
  33133. 5, 1, 3, 1, 6, 4, 0, 0,
  33134. 5, 3, 4, 2, 2, 2, 4, 0,
  33135. 2, 0, 1, 1, 6, 0, 6, 2,
  33136. // vertex alias (for same vertex on different faces)
  33137. 0, 4,
  33138. 3, 3,
  33139. 4, 4,
  33140. 3, 1,
  33141. 4, 2,
  33142. 4, 4,
  33143. 0, 2,
  33144. 1, 1,
  33145. 2, 2,
  33146. 3, 3,
  33147. 1, 3,
  33148. 2, 4 // 23: B + 12
  33149. ];
  33150. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33151. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33152. // First island of uv mapping
  33153. // v = 4h 3+ 2
  33154. // v = 3h 9+ 4
  33155. // v = 2h 9+ 5 B
  33156. // v = 1h 9 1 0
  33157. // v = 0h 3 8 7 A
  33158. // u = 0 1 2 3 4 5 6 *a
  33159. // Second island of uv mapping
  33160. // v = 4h 0+ B+ 4+
  33161. // v = 3h A+ 2+
  33162. // v = 2h 7+ 6 3+
  33163. // v = 1h 8+ 3+
  33164. // v = 0h
  33165. // u = 0 1 2 3 4 5 6 *a
  33166. // Face layout on texture UV mapping
  33167. // ============
  33168. // \ 4 /\ 16 / ======
  33169. // \ / \ / /\ 11 /
  33170. // \/ 7 \/ / \ /
  33171. // ======= / 10 \/
  33172. // /\ 17 /\ =======
  33173. // / \ / \ \ 15 /\
  33174. // / 8 \/ 12 \ \ / \
  33175. // ============ \/ 6 \
  33176. // \ 18 /\ ============
  33177. // \ / \ \ 5 /\ 0 /
  33178. // \/ 13 \ \ / \ /
  33179. // ======= \/ 1 \/
  33180. // =============
  33181. // /\ 19 /\ 2 /\
  33182. // / \ / \ / \
  33183. // / 14 \/ 9 \/ 3 \
  33184. // ===================
  33185. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33186. var ustep = 138 / 1024;
  33187. var vstep = 239 / 1024;
  33188. var uoffset = 60 / 1024;
  33189. var voffset = 26 / 1024;
  33190. // Second island should have margin, not to touch the first island
  33191. // avoid any borderline artefact in pixel rounding
  33192. var island_u_offset = -40 / 1024;
  33193. var island_v_offset = +20 / 1024;
  33194. // face is either island 0 or 1 :
  33195. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33196. var island = [
  33197. 0, 0, 0, 0, 1,
  33198. 0, 0, 1, 1, 0,
  33199. 0, 0, 1, 1, 0,
  33200. 0, 1, 1, 1, 0 // 15 - 19
  33201. ];
  33202. var indices = new Array();
  33203. var positions = new Array();
  33204. var normals = new Array();
  33205. var uvs = new Array();
  33206. var current_indice = 0;
  33207. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33208. var face_vertex_pos = new Array(3);
  33209. var face_vertex_uv = new Array(3);
  33210. var v012;
  33211. for (v012 = 0; v012 < 3; v012++) {
  33212. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33213. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33214. }
  33215. // create all with normals
  33216. for (var face = 0; face < 20; face++) {
  33217. // 3 vertex per face
  33218. for (v012 = 0; v012 < 3; v012++) {
  33219. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33220. var v_id = ico_indices[3 * face + v012];
  33221. // vertex have 3D position (x,y,z)
  33222. 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]);
  33223. // Normalize to get normal, then scale to radius
  33224. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33225. // uv Coordinates from vertex ID
  33226. 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);
  33227. }
  33228. // Subdivide the face (interpolate pos, norm, uv)
  33229. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33230. // - norm is linear interpolation of vertex corner normal
  33231. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33232. // - uv is linear interpolation
  33233. //
  33234. // Topology is as below for sub-divide by 2
  33235. // vertex shown as v0,v1,v2
  33236. // interp index is i1 to progress in range [v0,v1[
  33237. // interp index is i2 to progress in range [v0,v2[
  33238. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33239. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33240. //
  33241. //
  33242. // i2 v2
  33243. // ^ ^
  33244. // / / \
  33245. // / / \
  33246. // / / \
  33247. // / / (0,1) \
  33248. // / #---------\
  33249. // / / \ (0,0)'/ \
  33250. // / / \ / \
  33251. // / / \ / \
  33252. // / / (0,0) \ / (1,0) \
  33253. // / #---------#---------\
  33254. // v0 v1
  33255. //
  33256. // --------------------> i1
  33257. //
  33258. // interp of (i1,i2):
  33259. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33260. // along i1 : lerp(x0,x1, i1/(S-i2))
  33261. //
  33262. // centroid of triangle is needed to get help normal computation
  33263. // (c1,c2) are used for centroid location
  33264. var interp_vertex = function (i1, i2, c1, c2) {
  33265. // vertex is interpolated from
  33266. // - face_vertex_pos[0..2]
  33267. // - face_vertex_uv[0..2]
  33268. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33269. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33270. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33271. pos_interp.normalize();
  33272. var vertex_normal;
  33273. if (flat) {
  33274. // in flat mode, recalculate normal as face centroid normal
  33275. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33276. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33277. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33278. }
  33279. else {
  33280. // in smooth mode, recalculate normal from each single vertex position
  33281. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33282. }
  33283. // Vertex normal need correction due to X,Y,Z radius scaling
  33284. vertex_normal.x /= radiusX;
  33285. vertex_normal.y /= radiusY;
  33286. vertex_normal.z /= radiusZ;
  33287. vertex_normal.normalize();
  33288. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33289. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33290. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33291. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33292. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33293. uvs.push(uv_interp.x, uv_interp.y);
  33294. // push each vertex has member of a face
  33295. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33296. indices.push(current_indice);
  33297. current_indice++;
  33298. };
  33299. for (var i2 = 0; i2 < subdivisions; i2++) {
  33300. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33301. // face : (i1,i2) for /\ :
  33302. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33303. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33304. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33305. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33306. if (i1 + i2 + 1 < subdivisions) {
  33307. // face : (i1,i2)' for \/ :
  33308. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33309. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33310. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33311. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33312. }
  33313. }
  33314. }
  33315. }
  33316. // Sides
  33317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33318. // Result
  33319. var vertexData = new VertexData();
  33320. vertexData.indices = indices;
  33321. vertexData.positions = positions;
  33322. vertexData.normals = normals;
  33323. vertexData.uvs = uvs;
  33324. return vertexData;
  33325. };
  33326. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33327. /**
  33328. * Creates the VertexData of the Polyhedron.
  33329. */
  33330. VertexData.CreatePolyhedron = function (options) {
  33331. // provided polyhedron types :
  33332. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33333. // 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)
  33334. var polyhedra = [];
  33335. 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]] };
  33336. 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]] };
  33337. polyhedra[2] = {
  33338. 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]],
  33339. 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]]
  33340. };
  33341. polyhedra[3] = {
  33342. 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]],
  33343. 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]]
  33344. };
  33345. polyhedra[4] = {
  33346. 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]],
  33347. 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]]
  33348. };
  33349. 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]] };
  33350. 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]] };
  33351. 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]] };
  33352. 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]] };
  33353. 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]] };
  33354. 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]] };
  33355. 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]] };
  33356. 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]] };
  33357. 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]] };
  33358. polyhedra[14] = {
  33359. 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]],
  33360. 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]]
  33361. };
  33362. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33363. var size = options.size;
  33364. var sizeX = options.sizeX || size || 1;
  33365. var sizeY = options.sizeY || size || 1;
  33366. var sizeZ = options.sizeZ || size || 1;
  33367. var data = options.custom || polyhedra[type];
  33368. var nbfaces = data.face.length;
  33369. var faceUV = options.faceUV || new Array(nbfaces);
  33370. var faceColors = options.faceColors;
  33371. var flat = (options.flat === undefined) ? true : options.flat;
  33372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33373. var positions = new Array();
  33374. var indices = new Array();
  33375. var normals = new Array();
  33376. var uvs = new Array();
  33377. var colors = new Array();
  33378. var index = 0;
  33379. var faceIdx = 0; // face cursor in the array "indexes"
  33380. var indexes = new Array();
  33381. var i = 0;
  33382. var f = 0;
  33383. var u, v, ang, x, y, tmp;
  33384. // default face colors and UV if undefined
  33385. if (flat) {
  33386. for (f = 0; f < nbfaces; f++) {
  33387. if (faceColors && faceColors[f] === undefined) {
  33388. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33389. }
  33390. if (faceUV && faceUV[f] === undefined) {
  33391. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33392. }
  33393. }
  33394. }
  33395. if (!flat) {
  33396. for (i = 0; i < data.vertex.length; i++) {
  33397. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33398. uvs.push(0, 0);
  33399. }
  33400. for (f = 0; f < nbfaces; f++) {
  33401. for (i = 0; i < data.face[f].length - 2; i++) {
  33402. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33403. }
  33404. }
  33405. }
  33406. else {
  33407. for (f = 0; f < nbfaces; f++) {
  33408. var fl = data.face[f].length; // number of vertices of the current face
  33409. ang = 2 * Math.PI / fl;
  33410. x = 0.5 * Math.tan(ang / 2);
  33411. y = 0.5;
  33412. // positions, uvs, colors
  33413. for (i = 0; i < fl; i++) {
  33414. // positions
  33415. 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);
  33416. indexes.push(index);
  33417. index++;
  33418. // uvs
  33419. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33420. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33421. uvs.push(u, v);
  33422. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33423. y = x * Math.sin(ang) + y * Math.cos(ang);
  33424. x = tmp;
  33425. // colors
  33426. if (faceColors) {
  33427. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33428. }
  33429. }
  33430. // indices from indexes
  33431. for (i = 0; i < fl - 2; i++) {
  33432. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33433. }
  33434. faceIdx += fl;
  33435. }
  33436. }
  33437. VertexData.ComputeNormals(positions, indices, normals);
  33438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33439. var vertexData = new VertexData();
  33440. vertexData.positions = positions;
  33441. vertexData.indices = indices;
  33442. vertexData.normals = normals;
  33443. vertexData.uvs = uvs;
  33444. if (faceColors && flat) {
  33445. vertexData.colors = colors;
  33446. }
  33447. return vertexData;
  33448. };
  33449. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33450. /**
  33451. * Creates the VertexData of the Torus Knot.
  33452. */
  33453. VertexData.CreateTorusKnot = function (options) {
  33454. var indices = new Array();
  33455. var positions = new Array();
  33456. var normals = new Array();
  33457. var uvs = new Array();
  33458. var radius = options.radius || 2;
  33459. var tube = options.tube || 0.5;
  33460. var radialSegments = options.radialSegments || 32;
  33461. var tubularSegments = options.tubularSegments || 32;
  33462. var p = options.p || 2;
  33463. var q = options.q || 3;
  33464. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33465. // Helper
  33466. var getPos = function (angle) {
  33467. var cu = Math.cos(angle);
  33468. var su = Math.sin(angle);
  33469. var quOverP = q / p * angle;
  33470. var cs = Math.cos(quOverP);
  33471. var tx = radius * (2 + cs) * 0.5 * cu;
  33472. var ty = radius * (2 + cs) * su * 0.5;
  33473. var tz = radius * Math.sin(quOverP) * 0.5;
  33474. return new BABYLON.Vector3(tx, ty, tz);
  33475. };
  33476. // Vertices
  33477. var i;
  33478. var j;
  33479. for (i = 0; i <= radialSegments; i++) {
  33480. var modI = i % radialSegments;
  33481. var u = modI / radialSegments * 2 * p * Math.PI;
  33482. var p1 = getPos(u);
  33483. var p2 = getPos(u + 0.01);
  33484. var tang = p2.subtract(p1);
  33485. var n = p2.add(p1);
  33486. var bitan = BABYLON.Vector3.Cross(tang, n);
  33487. n = BABYLON.Vector3.Cross(bitan, tang);
  33488. bitan.normalize();
  33489. n.normalize();
  33490. for (j = 0; j < tubularSegments; j++) {
  33491. var modJ = j % tubularSegments;
  33492. var v = modJ / tubularSegments * 2 * Math.PI;
  33493. var cx = -tube * Math.cos(v);
  33494. var cy = tube * Math.sin(v);
  33495. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33496. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33497. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33498. uvs.push(i / radialSegments);
  33499. uvs.push(j / tubularSegments);
  33500. }
  33501. }
  33502. for (i = 0; i < radialSegments; i++) {
  33503. for (j = 0; j < tubularSegments; j++) {
  33504. var jNext = (j + 1) % tubularSegments;
  33505. var a = i * tubularSegments + j;
  33506. var b = (i + 1) * tubularSegments + j;
  33507. var c = (i + 1) * tubularSegments + jNext;
  33508. var d = i * tubularSegments + jNext;
  33509. indices.push(d);
  33510. indices.push(b);
  33511. indices.push(a);
  33512. indices.push(d);
  33513. indices.push(c);
  33514. indices.push(b);
  33515. }
  33516. }
  33517. // Normals
  33518. VertexData.ComputeNormals(positions, indices, normals);
  33519. // Sides
  33520. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33521. // Result
  33522. var vertexData = new VertexData();
  33523. vertexData.indices = indices;
  33524. vertexData.positions = positions;
  33525. vertexData.normals = normals;
  33526. vertexData.uvs = uvs;
  33527. return vertexData;
  33528. };
  33529. // Tools
  33530. /**
  33531. * @param {any} - positions (number[] or Float32Array)
  33532. * @param {any} - indices (number[] or Uint16Array)
  33533. * @param {any} - normals (number[] or Float32Array)
  33534. * options (optional) :
  33535. * facetPositions : optional array of facet positions (vector3)
  33536. * facetNormals : optional array of facet normals (vector3)
  33537. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33538. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33539. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33540. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33541. * bInfo : optional bounding info, required for facetPartitioning computation
  33542. * useRightHandedSystem: optional boolean to for right handed system computation
  33543. * depthSort : optional boolean to enable the facet depth sort computation
  33544. * distanceTo : optional Vector3 to compute the facet depth from this location
  33545. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33546. */
  33547. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33548. // temporary scalar variables
  33549. var index = 0; // facet index
  33550. var p1p2x = 0.0; // p1p2 vector x coordinate
  33551. var p1p2y = 0.0; // p1p2 vector y coordinate
  33552. var p1p2z = 0.0; // p1p2 vector z coordinate
  33553. var p3p2x = 0.0; // p3p2 vector x coordinate
  33554. var p3p2y = 0.0; // p3p2 vector y coordinate
  33555. var p3p2z = 0.0; // p3p2 vector z coordinate
  33556. var faceNormalx = 0.0; // facet normal x coordinate
  33557. var faceNormaly = 0.0; // facet normal y coordinate
  33558. var faceNormalz = 0.0; // facet normal z coordinate
  33559. var length = 0.0; // facet normal length before normalization
  33560. var v1x = 0; // vector1 x index in the positions array
  33561. var v1y = 0; // vector1 y index in the positions array
  33562. var v1z = 0; // vector1 z index in the positions array
  33563. var v2x = 0; // vector2 x index in the positions array
  33564. var v2y = 0; // vector2 y index in the positions array
  33565. var v2z = 0; // vector2 z index in the positions array
  33566. var v3x = 0; // vector3 x index in the positions array
  33567. var v3y = 0; // vector3 y index in the positions array
  33568. var v3z = 0; // vector3 z index in the positions array
  33569. var computeFacetNormals = false;
  33570. var computeFacetPositions = false;
  33571. var computeFacetPartitioning = false;
  33572. var computeDepthSort = false;
  33573. var faceNormalSign = 1;
  33574. var ratio = 0;
  33575. var distanceTo = null;
  33576. if (options) {
  33577. computeFacetNormals = (options.facetNormals) ? true : false;
  33578. computeFacetPositions = (options.facetPositions) ? true : false;
  33579. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33580. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33581. ratio = options.ratio || 0;
  33582. computeDepthSort = (options.depthSort) ? true : false;
  33583. distanceTo = (options.distanceTo);
  33584. if (computeDepthSort) {
  33585. if (distanceTo === undefined) {
  33586. distanceTo = BABYLON.Vector3.Zero();
  33587. }
  33588. var depthSortedFacets = options.depthSortedFacets;
  33589. }
  33590. }
  33591. // facetPartitioning reinit if needed
  33592. var xSubRatio = 0;
  33593. var ySubRatio = 0;
  33594. var zSubRatio = 0;
  33595. var subSq = 0;
  33596. if (computeFacetPartitioning && options && options.bbSize) {
  33597. var ox = 0; // X partitioning index for facet position
  33598. var oy = 0; // Y partinioning index for facet position
  33599. var oz = 0; // Z partinioning index for facet position
  33600. var b1x = 0; // X partitioning index for facet v1 vertex
  33601. var b1y = 0; // Y partitioning index for facet v1 vertex
  33602. var b1z = 0; // z partitioning index for facet v1 vertex
  33603. var b2x = 0; // X partitioning index for facet v2 vertex
  33604. var b2y = 0; // Y partitioning index for facet v2 vertex
  33605. var b2z = 0; // Z partitioning index for facet v2 vertex
  33606. var b3x = 0; // X partitioning index for facet v3 vertex
  33607. var b3y = 0; // Y partitioning index for facet v3 vertex
  33608. var b3z = 0; // Z partitioning index for facet v3 vertex
  33609. var block_idx_o = 0; // facet barycenter block index
  33610. var block_idx_v1 = 0; // v1 vertex block index
  33611. var block_idx_v2 = 0; // v2 vertex block index
  33612. var block_idx_v3 = 0; // v3 vertex block index
  33613. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33614. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33615. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33616. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33617. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33618. subSq = options.subDiv.max * options.subDiv.max;
  33619. options.facetPartitioning.length = 0;
  33620. }
  33621. // reset the normals
  33622. for (index = 0; index < positions.length; index++) {
  33623. normals[index] = 0.0;
  33624. }
  33625. // Loop : 1 indice triplet = 1 facet
  33626. var nbFaces = (indices.length / 3) | 0;
  33627. for (index = 0; index < nbFaces; index++) {
  33628. // get the indexes of the coordinates of each vertex of the facet
  33629. v1x = indices[index * 3] * 3;
  33630. v1y = v1x + 1;
  33631. v1z = v1x + 2;
  33632. v2x = indices[index * 3 + 1] * 3;
  33633. v2y = v2x + 1;
  33634. v2z = v2x + 2;
  33635. v3x = indices[index * 3 + 2] * 3;
  33636. v3y = v3x + 1;
  33637. v3z = v3x + 2;
  33638. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33639. p1p2y = positions[v1y] - positions[v2y];
  33640. p1p2z = positions[v1z] - positions[v2z];
  33641. p3p2x = positions[v3x] - positions[v2x];
  33642. p3p2y = positions[v3y] - positions[v2y];
  33643. p3p2z = positions[v3z] - positions[v2z];
  33644. // compute the face normal with the cross product
  33645. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33646. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33647. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33648. // normalize this normal and store it in the array facetData
  33649. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33650. length = (length === 0) ? 1.0 : length;
  33651. faceNormalx /= length;
  33652. faceNormaly /= length;
  33653. faceNormalz /= length;
  33654. if (computeFacetNormals && options) {
  33655. options.facetNormals[index].x = faceNormalx;
  33656. options.facetNormals[index].y = faceNormaly;
  33657. options.facetNormals[index].z = faceNormalz;
  33658. }
  33659. if (computeFacetPositions && options) {
  33660. // compute and the facet barycenter coordinates in the array facetPositions
  33661. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33662. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33663. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33664. }
  33665. if (computeFacetPartitioning && options) {
  33666. // store the facet indexes in arrays in the main facetPartitioning array :
  33667. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33668. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33669. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33670. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33671. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33672. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33673. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33674. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33675. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33676. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33677. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33678. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33679. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33680. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33681. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33682. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33683. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33684. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33685. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33686. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33687. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33688. // push each facet index in each block containing the vertex
  33689. options.facetPartitioning[block_idx_v1].push(index);
  33690. if (block_idx_v2 != block_idx_v1) {
  33691. options.facetPartitioning[block_idx_v2].push(index);
  33692. }
  33693. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33694. options.facetPartitioning[block_idx_v3].push(index);
  33695. }
  33696. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33697. options.facetPartitioning[block_idx_o].push(index);
  33698. }
  33699. }
  33700. if (computeDepthSort && options && options.facetPositions) {
  33701. var dsf = depthSortedFacets[index];
  33702. dsf.ind = index * 3;
  33703. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33704. }
  33705. // compute the normals anyway
  33706. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33707. normals[v1y] += faceNormaly;
  33708. normals[v1z] += faceNormalz;
  33709. normals[v2x] += faceNormalx;
  33710. normals[v2y] += faceNormaly;
  33711. normals[v2z] += faceNormalz;
  33712. normals[v3x] += faceNormalx;
  33713. normals[v3y] += faceNormaly;
  33714. normals[v3z] += faceNormalz;
  33715. }
  33716. // last normalization of each normal
  33717. for (index = 0; index < normals.length / 3; index++) {
  33718. faceNormalx = normals[index * 3];
  33719. faceNormaly = normals[index * 3 + 1];
  33720. faceNormalz = normals[index * 3 + 2];
  33721. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33722. length = (length === 0) ? 1.0 : length;
  33723. faceNormalx /= length;
  33724. faceNormaly /= length;
  33725. faceNormalz /= length;
  33726. normals[index * 3] = faceNormalx;
  33727. normals[index * 3 + 1] = faceNormaly;
  33728. normals[index * 3 + 2] = faceNormalz;
  33729. }
  33730. };
  33731. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33732. var li = indices.length;
  33733. var ln = normals.length;
  33734. var i;
  33735. var n;
  33736. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33737. switch (sideOrientation) {
  33738. case BABYLON.Mesh.FRONTSIDE:
  33739. // nothing changed
  33740. break;
  33741. case BABYLON.Mesh.BACKSIDE:
  33742. var tmp;
  33743. // indices
  33744. for (i = 0; i < li; i += 3) {
  33745. tmp = indices[i];
  33746. indices[i] = indices[i + 2];
  33747. indices[i + 2] = tmp;
  33748. }
  33749. // normals
  33750. for (n = 0; n < ln; n++) {
  33751. normals[n] = -normals[n];
  33752. }
  33753. break;
  33754. case BABYLON.Mesh.DOUBLESIDE:
  33755. // positions
  33756. var lp = positions.length;
  33757. var l = lp / 3;
  33758. for (var p = 0; p < lp; p++) {
  33759. positions[lp + p] = positions[p];
  33760. }
  33761. // indices
  33762. for (i = 0; i < li; i += 3) {
  33763. indices[i + li] = indices[i + 2] + l;
  33764. indices[i + 1 + li] = indices[i + 1] + l;
  33765. indices[i + 2 + li] = indices[i] + l;
  33766. }
  33767. // normals
  33768. for (n = 0; n < ln; n++) {
  33769. normals[ln + n] = -normals[n];
  33770. }
  33771. // uvs
  33772. var lu = uvs.length;
  33773. var u = 0;
  33774. for (u = 0; u < lu; u++) {
  33775. uvs[u + lu] = uvs[u];
  33776. }
  33777. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33778. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33779. u = 0;
  33780. for (i = 0; i < lu / 2; i++) {
  33781. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33782. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33783. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33784. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33785. u += 2;
  33786. }
  33787. break;
  33788. }
  33789. };
  33790. /**
  33791. * Creates a new VertexData from the imported parameters.
  33792. */
  33793. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33794. var vertexData = new VertexData();
  33795. // positions
  33796. var positions = parsedVertexData.positions;
  33797. if (positions) {
  33798. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33799. }
  33800. // normals
  33801. var normals = parsedVertexData.normals;
  33802. if (normals) {
  33803. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33804. }
  33805. // tangents
  33806. var tangents = parsedVertexData.tangents;
  33807. if (tangents) {
  33808. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33809. }
  33810. // uvs
  33811. var uvs = parsedVertexData.uvs;
  33812. if (uvs) {
  33813. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33814. }
  33815. // uv2s
  33816. var uv2s = parsedVertexData.uv2s;
  33817. if (uv2s) {
  33818. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33819. }
  33820. // uv3s
  33821. var uv3s = parsedVertexData.uv3s;
  33822. if (uv3s) {
  33823. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33824. }
  33825. // uv4s
  33826. var uv4s = parsedVertexData.uv4s;
  33827. if (uv4s) {
  33828. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33829. }
  33830. // uv5s
  33831. var uv5s = parsedVertexData.uv5s;
  33832. if (uv5s) {
  33833. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33834. }
  33835. // uv6s
  33836. var uv6s = parsedVertexData.uv6s;
  33837. if (uv6s) {
  33838. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33839. }
  33840. // colors
  33841. var colors = parsedVertexData.colors;
  33842. if (colors) {
  33843. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33844. }
  33845. // matricesIndices
  33846. var matricesIndices = parsedVertexData.matricesIndices;
  33847. if (matricesIndices) {
  33848. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33849. }
  33850. // matricesWeights
  33851. var matricesWeights = parsedVertexData.matricesWeights;
  33852. if (matricesWeights) {
  33853. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33854. }
  33855. // indices
  33856. var indices = parsedVertexData.indices;
  33857. if (indices) {
  33858. vertexData.indices = indices;
  33859. }
  33860. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33861. };
  33862. return VertexData;
  33863. }());
  33864. BABYLON.VertexData = VertexData;
  33865. })(BABYLON || (BABYLON = {}));
  33866. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33867. var BABYLON;
  33868. (function (BABYLON) {
  33869. /**
  33870. * Class used to store geometry data (vertex buffers + index buffer)
  33871. */
  33872. var Geometry = /** @class */ (function () {
  33873. /**
  33874. * Creates a new geometry
  33875. * @param id defines the unique ID
  33876. * @param scene defines the hosting scene
  33877. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33878. * @param updatable defines if geometry must be updatable (false by default)
  33879. * @param mesh defines the mesh that will be associated with the geometry
  33880. */
  33881. function Geometry(id, scene, vertexData, updatable, mesh) {
  33882. if (updatable === void 0) { updatable = false; }
  33883. if (mesh === void 0) { mesh = null; }
  33884. /**
  33885. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33886. */
  33887. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33888. this._totalVertices = 0;
  33889. this._isDisposed = false;
  33890. this._indexBufferIsUpdatable = false;
  33891. this.id = id;
  33892. this._engine = scene.getEngine();
  33893. this._meshes = [];
  33894. this._scene = scene;
  33895. //Init vertex buffer cache
  33896. this._vertexBuffers = {};
  33897. this._indices = [];
  33898. this._updatable = updatable;
  33899. // vertexData
  33900. if (vertexData) {
  33901. this.setAllVerticesData(vertexData, updatable);
  33902. }
  33903. else {
  33904. this._totalVertices = 0;
  33905. this._indices = [];
  33906. }
  33907. if (this._engine.getCaps().vertexArrayObject) {
  33908. this._vertexArrayObjects = {};
  33909. }
  33910. // applyToMesh
  33911. if (mesh) {
  33912. if (mesh.getClassName() === "LinesMesh") {
  33913. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33914. this.updateExtend();
  33915. }
  33916. this.applyToMesh(mesh);
  33917. mesh.computeWorldMatrix(true);
  33918. }
  33919. }
  33920. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33921. /**
  33922. * 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
  33923. */
  33924. get: function () {
  33925. return this._boundingBias;
  33926. },
  33927. /**
  33928. * 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
  33929. */
  33930. set: function (value) {
  33931. if (this._boundingBias && this._boundingBias.equals(value)) {
  33932. return;
  33933. }
  33934. this._boundingBias = value.clone();
  33935. this.updateBoundingInfo(true, null);
  33936. },
  33937. enumerable: true,
  33938. configurable: true
  33939. });
  33940. /**
  33941. * Static function used to attach a new empty geometry to a mesh
  33942. * @param mesh defines the mesh to attach the geometry to
  33943. * @returns the new {BABYLON.Geometry}
  33944. */
  33945. Geometry.CreateGeometryForMesh = function (mesh) {
  33946. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  33947. geometry.applyToMesh(mesh);
  33948. return geometry;
  33949. };
  33950. Object.defineProperty(Geometry.prototype, "extend", {
  33951. /**
  33952. * Gets the current extend of the geometry
  33953. */
  33954. get: function () {
  33955. return this._extend;
  33956. },
  33957. enumerable: true,
  33958. configurable: true
  33959. });
  33960. /**
  33961. * Gets the hosting scene
  33962. * @returns the hosting {BABYLON.Scene}
  33963. */
  33964. Geometry.prototype.getScene = function () {
  33965. return this._scene;
  33966. };
  33967. /**
  33968. * Gets the hosting engine
  33969. * @returns the hosting {BABYLON.Engine}
  33970. */
  33971. Geometry.prototype.getEngine = function () {
  33972. return this._engine;
  33973. };
  33974. /**
  33975. * Defines if the geometry is ready to use
  33976. * @returns true if the geometry is ready to be used
  33977. */
  33978. Geometry.prototype.isReady = function () {
  33979. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33980. };
  33981. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  33982. /**
  33983. * Gets a value indicating that the geometry should not be serialized
  33984. */
  33985. get: function () {
  33986. for (var index = 0; index < this._meshes.length; index++) {
  33987. if (!this._meshes[index].doNotSerialize) {
  33988. return false;
  33989. }
  33990. }
  33991. return true;
  33992. },
  33993. enumerable: true,
  33994. configurable: true
  33995. });
  33996. /** @ignore */
  33997. Geometry.prototype._rebuild = function () {
  33998. if (this._vertexArrayObjects) {
  33999. this._vertexArrayObjects = {};
  34000. }
  34001. // Index buffer
  34002. if (this._meshes.length !== 0 && this._indices) {
  34003. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34004. }
  34005. // Vertex buffers
  34006. for (var key in this._vertexBuffers) {
  34007. var vertexBuffer = this._vertexBuffers[key];
  34008. vertexBuffer._rebuild();
  34009. }
  34010. };
  34011. /**
  34012. * Affects all gemetry data in one call
  34013. * @param vertexData defines the geometry data
  34014. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34015. */
  34016. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34017. vertexData.applyToGeometry(this, updatable);
  34018. this.notifyUpdate();
  34019. };
  34020. /**
  34021. * Set specific vertex data
  34022. * @param kind defines the data kind (Position, normal, etc...)
  34023. * @param data defines the vertex data to use
  34024. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34025. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34026. */
  34027. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34028. if (updatable === void 0) { updatable = false; }
  34029. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34030. this.setVerticesBuffer(buffer);
  34031. };
  34032. /**
  34033. * Removes a specific vertex data
  34034. * @param kind defines the data kind (Position, normal, etc...)
  34035. */
  34036. Geometry.prototype.removeVerticesData = function (kind) {
  34037. if (this._vertexBuffers[kind]) {
  34038. this._vertexBuffers[kind].dispose();
  34039. delete this._vertexBuffers[kind];
  34040. }
  34041. };
  34042. /**
  34043. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34044. * @param buffer defines the vertex buffer to use
  34045. */
  34046. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34047. var kind = buffer.getKind();
  34048. if (this._vertexBuffers[kind]) {
  34049. this._vertexBuffers[kind].dispose();
  34050. }
  34051. this._vertexBuffers[kind] = buffer;
  34052. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34053. var data = buffer.getData();
  34054. var stride = buffer.getStrideSize();
  34055. this._totalVertices = data.length / stride;
  34056. this.updateExtend(data, stride);
  34057. this._resetPointsArrayCache();
  34058. var meshes = this._meshes;
  34059. var numOfMeshes = meshes.length;
  34060. for (var index = 0; index < numOfMeshes; index++) {
  34061. var mesh = meshes[index];
  34062. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34063. mesh._createGlobalSubMesh(false);
  34064. mesh.computeWorldMatrix(true);
  34065. }
  34066. }
  34067. this.notifyUpdate(kind);
  34068. if (this._vertexArrayObjects) {
  34069. this._disposeVertexArrayObjects();
  34070. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34071. }
  34072. };
  34073. /**
  34074. * Update a specific vertex buffer
  34075. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34076. * It will do nothing if the buffer is not updatable
  34077. * @param kind defines the data kind (Position, normal, etc...)
  34078. * @param data defines the data to use
  34079. * @param offset defines the offset in the target buffer where to store the data
  34080. */
  34081. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34082. var vertexBuffer = this.getVertexBuffer(kind);
  34083. if (!vertexBuffer) {
  34084. return;
  34085. }
  34086. vertexBuffer.updateDirectly(data, offset);
  34087. this.notifyUpdate(kind);
  34088. };
  34089. /**
  34090. * Update a specific vertex buffer
  34091. * This function will create a new buffer if the current one is not updatable
  34092. * @param kind defines the data kind (Position, normal, etc...)
  34093. * @param data defines the data to use
  34094. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34095. */
  34096. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34097. if (updateExtends === void 0) { updateExtends = false; }
  34098. var vertexBuffer = this.getVertexBuffer(kind);
  34099. if (!vertexBuffer) {
  34100. return;
  34101. }
  34102. vertexBuffer.update(data);
  34103. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34104. var stride = vertexBuffer.getStrideSize();
  34105. this._totalVertices = data.length / stride;
  34106. this.updateBoundingInfo(updateExtends, data);
  34107. }
  34108. this.notifyUpdate(kind);
  34109. };
  34110. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34111. if (updateExtends) {
  34112. this.updateExtend(data);
  34113. }
  34114. var meshes = this._meshes;
  34115. var numOfMeshes = meshes.length;
  34116. this._resetPointsArrayCache();
  34117. for (var index = 0; index < numOfMeshes; index++) {
  34118. var mesh = meshes[index];
  34119. if (updateExtends) {
  34120. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34121. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34122. var subMesh = mesh.subMeshes[subIndex];
  34123. subMesh.refreshBoundingInfo();
  34124. }
  34125. }
  34126. }
  34127. };
  34128. /** @ignore */
  34129. Geometry.prototype._bind = function (effect, indexToBind) {
  34130. if (!effect) {
  34131. return;
  34132. }
  34133. if (indexToBind === undefined) {
  34134. indexToBind = this._indexBuffer;
  34135. }
  34136. var vbs = this.getVertexBuffers();
  34137. if (!vbs) {
  34138. return;
  34139. }
  34140. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34141. this._engine.bindBuffers(vbs, indexToBind, effect);
  34142. return;
  34143. }
  34144. // Using VAO
  34145. if (!this._vertexArrayObjects[effect.key]) {
  34146. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34147. }
  34148. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34149. };
  34150. /**
  34151. * Gets total number of vertices
  34152. * @returns the total number of vertices
  34153. */
  34154. Geometry.prototype.getTotalVertices = function () {
  34155. if (!this.isReady()) {
  34156. return 0;
  34157. }
  34158. return this._totalVertices;
  34159. };
  34160. /**
  34161. * Gets a specific vertex data attached to this geometry
  34162. * @param kind defines the data kind (Position, normal, etc...)
  34163. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34164. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34165. * @returns a float array containing vertex data
  34166. */
  34167. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34168. var vertexBuffer = this.getVertexBuffer(kind);
  34169. if (!vertexBuffer) {
  34170. return null;
  34171. }
  34172. var orig = vertexBuffer.getData();
  34173. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34174. return orig;
  34175. }
  34176. else {
  34177. var len = orig.length;
  34178. var copy = [];
  34179. for (var i = 0; i < len; i++) {
  34180. copy.push(orig[i]);
  34181. }
  34182. return copy;
  34183. }
  34184. };
  34185. /**
  34186. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34187. * @param kind defines the data kind (Position, normal, etc...)
  34188. * @returns true if the vertex buffer with the specified kind is updatable
  34189. */
  34190. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34191. var vb = this._vertexBuffers[kind];
  34192. if (!vb) {
  34193. return false;
  34194. }
  34195. return vb.isUpdatable();
  34196. };
  34197. /**
  34198. * Gets a specific vertex buffer
  34199. * @param kind defines the data kind (Position, normal, etc...)
  34200. * @returns a {BABYLON.VertexBuffer}
  34201. */
  34202. Geometry.prototype.getVertexBuffer = function (kind) {
  34203. if (!this.isReady()) {
  34204. return null;
  34205. }
  34206. return this._vertexBuffers[kind];
  34207. };
  34208. /**
  34209. * Returns all vertex buffers
  34210. * @return an object holding all vertex buffers indexed by kind
  34211. */
  34212. Geometry.prototype.getVertexBuffers = function () {
  34213. if (!this.isReady()) {
  34214. return null;
  34215. }
  34216. return this._vertexBuffers;
  34217. };
  34218. /**
  34219. * Gets a boolean indicating if specific vertex buffer is present
  34220. * @param kind defines the data kind (Position, normal, etc...)
  34221. * @returns true if data is present
  34222. */
  34223. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34224. if (!this._vertexBuffers) {
  34225. if (this._delayInfo) {
  34226. return this._delayInfo.indexOf(kind) !== -1;
  34227. }
  34228. return false;
  34229. }
  34230. return this._vertexBuffers[kind] !== undefined;
  34231. };
  34232. /**
  34233. * Gets a list of all attached data kinds (Position, normal, etc...)
  34234. * @returns a list of string containing all kinds
  34235. */
  34236. Geometry.prototype.getVerticesDataKinds = function () {
  34237. var result = [];
  34238. var kind;
  34239. if (!this._vertexBuffers && this._delayInfo) {
  34240. for (kind in this._delayInfo) {
  34241. result.push(kind);
  34242. }
  34243. }
  34244. else {
  34245. for (kind in this._vertexBuffers) {
  34246. result.push(kind);
  34247. }
  34248. }
  34249. return result;
  34250. };
  34251. /**
  34252. * Update index buffer
  34253. * @param indices defines the indices to store in the index buffer
  34254. * @param offset defines the offset in the target buffer where to store the data
  34255. */
  34256. Geometry.prototype.updateIndices = function (indices, offset) {
  34257. if (!this._indexBuffer) {
  34258. return;
  34259. }
  34260. if (!this._indexBufferIsUpdatable) {
  34261. this.setIndices(indices, null, true);
  34262. }
  34263. else {
  34264. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34265. }
  34266. };
  34267. /**
  34268. * Creates a new index buffer
  34269. * @param indices defines the indices to store in the index buffer
  34270. * @param totalVertices defines the total number of vertices (could be null)
  34271. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34272. */
  34273. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34274. if (totalVertices === void 0) { totalVertices = null; }
  34275. if (updatable === void 0) { updatable = false; }
  34276. if (this._indexBuffer) {
  34277. this._engine._releaseBuffer(this._indexBuffer);
  34278. }
  34279. this._disposeVertexArrayObjects();
  34280. this._indices = indices;
  34281. this._indexBufferIsUpdatable = updatable;
  34282. if (this._meshes.length !== 0 && this._indices) {
  34283. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34284. }
  34285. if (totalVertices != undefined) {
  34286. this._totalVertices = totalVertices;
  34287. }
  34288. var meshes = this._meshes;
  34289. var numOfMeshes = meshes.length;
  34290. for (var index = 0; index < numOfMeshes; index++) {
  34291. meshes[index]._createGlobalSubMesh(true);
  34292. }
  34293. this.notifyUpdate();
  34294. };
  34295. /**
  34296. * Return the total number of indices
  34297. * @returns the total number of indices
  34298. */
  34299. Geometry.prototype.getTotalIndices = function () {
  34300. if (!this.isReady()) {
  34301. return 0;
  34302. }
  34303. return this._indices.length;
  34304. };
  34305. /**
  34306. * Gets the index buffer array
  34307. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34308. * @returns the index buffer array
  34309. */
  34310. Geometry.prototype.getIndices = function (copyWhenShared) {
  34311. if (!this.isReady()) {
  34312. return null;
  34313. }
  34314. var orig = this._indices;
  34315. if (!copyWhenShared || this._meshes.length === 1) {
  34316. return orig;
  34317. }
  34318. else {
  34319. var len = orig.length;
  34320. var copy = [];
  34321. for (var i = 0; i < len; i++) {
  34322. copy.push(orig[i]);
  34323. }
  34324. return copy;
  34325. }
  34326. };
  34327. /**
  34328. * Gets the index buffer
  34329. * @return the index buffer
  34330. */
  34331. Geometry.prototype.getIndexBuffer = function () {
  34332. if (!this.isReady()) {
  34333. return null;
  34334. }
  34335. return this._indexBuffer;
  34336. };
  34337. /** @ignore */
  34338. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34339. if (effect === void 0) { effect = null; }
  34340. if (!effect || !this._vertexArrayObjects) {
  34341. return;
  34342. }
  34343. if (this._vertexArrayObjects[effect.key]) {
  34344. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34345. delete this._vertexArrayObjects[effect.key];
  34346. }
  34347. };
  34348. /**
  34349. * Release the associated resources for a specific mesh
  34350. * @param mesh defines the source mesh
  34351. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34352. */
  34353. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34354. var meshes = this._meshes;
  34355. var index = meshes.indexOf(mesh);
  34356. if (index === -1) {
  34357. return;
  34358. }
  34359. meshes.splice(index, 1);
  34360. mesh._geometry = null;
  34361. if (meshes.length === 0 && shouldDispose) {
  34362. this.dispose();
  34363. }
  34364. };
  34365. /**
  34366. * Apply current geometry to a given mesh
  34367. * @param mesh defines the mesh to apply geometry to
  34368. */
  34369. Geometry.prototype.applyToMesh = function (mesh) {
  34370. if (mesh._geometry === this) {
  34371. return;
  34372. }
  34373. var previousGeometry = mesh._geometry;
  34374. if (previousGeometry) {
  34375. previousGeometry.releaseForMesh(mesh);
  34376. }
  34377. var meshes = this._meshes;
  34378. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34379. mesh._geometry = this;
  34380. this._scene.pushGeometry(this);
  34381. meshes.push(mesh);
  34382. if (this.isReady()) {
  34383. this._applyToMesh(mesh);
  34384. }
  34385. else {
  34386. mesh._boundingInfo = this._boundingInfo;
  34387. }
  34388. };
  34389. Geometry.prototype.updateExtend = function (data, stride) {
  34390. if (data === void 0) { data = null; }
  34391. if (!data) {
  34392. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34393. }
  34394. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34395. };
  34396. Geometry.prototype._applyToMesh = function (mesh) {
  34397. var numOfMeshes = this._meshes.length;
  34398. // vertexBuffers
  34399. for (var kind in this._vertexBuffers) {
  34400. if (numOfMeshes === 1) {
  34401. this._vertexBuffers[kind].create();
  34402. }
  34403. var buffer = this._vertexBuffers[kind].getBuffer();
  34404. if (buffer)
  34405. buffer.references = numOfMeshes;
  34406. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34407. if (!this._extend) {
  34408. this.updateExtend(this._vertexBuffers[kind].getData());
  34409. }
  34410. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34411. mesh._createGlobalSubMesh(false);
  34412. //bounding info was just created again, world matrix should be applied again.
  34413. mesh._updateBoundingInfo();
  34414. }
  34415. }
  34416. // indexBuffer
  34417. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34418. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34419. }
  34420. if (this._indexBuffer) {
  34421. this._indexBuffer.references = numOfMeshes;
  34422. }
  34423. };
  34424. Geometry.prototype.notifyUpdate = function (kind) {
  34425. if (this.onGeometryUpdated) {
  34426. this.onGeometryUpdated(this, kind);
  34427. }
  34428. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34429. var mesh = _a[_i];
  34430. mesh._markSubMeshesAsAttributesDirty();
  34431. }
  34432. };
  34433. /**
  34434. * Load the geometry if it was flagged as delay loaded
  34435. * @param scene defines the hosting scene
  34436. * @param onLoaded defines a callback called when the geometry is loaded
  34437. */
  34438. Geometry.prototype.load = function (scene, onLoaded) {
  34439. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34440. return;
  34441. }
  34442. if (this.isReady()) {
  34443. if (onLoaded) {
  34444. onLoaded();
  34445. }
  34446. return;
  34447. }
  34448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34449. this._queueLoad(scene, onLoaded);
  34450. };
  34451. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34452. var _this = this;
  34453. if (!this.delayLoadingFile) {
  34454. return;
  34455. }
  34456. scene._addPendingData(this);
  34457. scene._loadFile(this.delayLoadingFile, function (data) {
  34458. if (!_this._delayLoadingFunction) {
  34459. return;
  34460. }
  34461. _this._delayLoadingFunction(JSON.parse(data), _this);
  34462. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34463. _this._delayInfo = [];
  34464. scene._removePendingData(_this);
  34465. var meshes = _this._meshes;
  34466. var numOfMeshes = meshes.length;
  34467. for (var index = 0; index < numOfMeshes; index++) {
  34468. _this._applyToMesh(meshes[index]);
  34469. }
  34470. if (onLoaded) {
  34471. onLoaded();
  34472. }
  34473. }, undefined, true);
  34474. };
  34475. /**
  34476. * Invert the geometry to move from a right handed system to a left handed one.
  34477. */
  34478. Geometry.prototype.toLeftHanded = function () {
  34479. // Flip faces
  34480. var tIndices = this.getIndices(false);
  34481. if (tIndices != null && tIndices.length > 0) {
  34482. for (var i = 0; i < tIndices.length; i += 3) {
  34483. var tTemp = tIndices[i + 0];
  34484. tIndices[i + 0] = tIndices[i + 2];
  34485. tIndices[i + 2] = tTemp;
  34486. }
  34487. this.setIndices(tIndices);
  34488. }
  34489. // Negate position.z
  34490. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34491. if (tPositions != null && tPositions.length > 0) {
  34492. for (var i = 0; i < tPositions.length; i += 3) {
  34493. tPositions[i + 2] = -tPositions[i + 2];
  34494. }
  34495. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34496. }
  34497. // Negate normal.z
  34498. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34499. if (tNormals != null && tNormals.length > 0) {
  34500. for (var i = 0; i < tNormals.length; i += 3) {
  34501. tNormals[i + 2] = -tNormals[i + 2];
  34502. }
  34503. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34504. }
  34505. };
  34506. // Cache
  34507. /** @ignore */
  34508. Geometry.prototype._resetPointsArrayCache = function () {
  34509. this._positions = null;
  34510. };
  34511. /** @ignore */
  34512. Geometry.prototype._generatePointsArray = function () {
  34513. if (this._positions)
  34514. return true;
  34515. this._positions = [];
  34516. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34517. if (!data) {
  34518. return false;
  34519. }
  34520. for (var index = 0; index < data.length; index += 3) {
  34521. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34522. }
  34523. return true;
  34524. };
  34525. /**
  34526. * Gets a value indicating if the geometry is disposed
  34527. * @returns true if the geometry was disposed
  34528. */
  34529. Geometry.prototype.isDisposed = function () {
  34530. return this._isDisposed;
  34531. };
  34532. Geometry.prototype._disposeVertexArrayObjects = function () {
  34533. if (this._vertexArrayObjects) {
  34534. for (var kind in this._vertexArrayObjects) {
  34535. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34536. }
  34537. this._vertexArrayObjects = {};
  34538. }
  34539. };
  34540. /**
  34541. * Free all associated resources
  34542. */
  34543. Geometry.prototype.dispose = function () {
  34544. var meshes = this._meshes;
  34545. var numOfMeshes = meshes.length;
  34546. var index;
  34547. for (index = 0; index < numOfMeshes; index++) {
  34548. this.releaseForMesh(meshes[index]);
  34549. }
  34550. this._meshes = [];
  34551. this._disposeVertexArrayObjects();
  34552. for (var kind in this._vertexBuffers) {
  34553. this._vertexBuffers[kind].dispose();
  34554. }
  34555. this._vertexBuffers = {};
  34556. this._totalVertices = 0;
  34557. if (this._indexBuffer) {
  34558. this._engine._releaseBuffer(this._indexBuffer);
  34559. }
  34560. this._indexBuffer = null;
  34561. this._indices = [];
  34562. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34563. this.delayLoadingFile = null;
  34564. this._delayLoadingFunction = null;
  34565. this._delayInfo = [];
  34566. this._boundingInfo = null;
  34567. this._scene.removeGeometry(this);
  34568. this._isDisposed = true;
  34569. };
  34570. /**
  34571. * Clone the current geometry into a new geometry
  34572. * @param id defines the unique ID of the new geometry
  34573. * @returns a new geometry object
  34574. */
  34575. Geometry.prototype.copy = function (id) {
  34576. var vertexData = new BABYLON.VertexData();
  34577. vertexData.indices = [];
  34578. var indices = this.getIndices();
  34579. if (indices) {
  34580. for (var index = 0; index < indices.length; index++) {
  34581. vertexData.indices.push(indices[index]);
  34582. }
  34583. }
  34584. var updatable = false;
  34585. var stopChecking = false;
  34586. var kind;
  34587. for (kind in this._vertexBuffers) {
  34588. // using slice() to make a copy of the array and not just reference it
  34589. var data = this.getVerticesData(kind);
  34590. if (data instanceof Float32Array) {
  34591. vertexData.set(new Float32Array(data), kind);
  34592. }
  34593. else {
  34594. vertexData.set(data.slice(0), kind);
  34595. }
  34596. if (!stopChecking) {
  34597. var vb = this.getVertexBuffer(kind);
  34598. if (vb) {
  34599. updatable = vb.isUpdatable();
  34600. stopChecking = !updatable;
  34601. }
  34602. }
  34603. }
  34604. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34605. geometry.delayLoadState = this.delayLoadState;
  34606. geometry.delayLoadingFile = this.delayLoadingFile;
  34607. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34608. for (kind in this._delayInfo) {
  34609. geometry._delayInfo = geometry._delayInfo || [];
  34610. geometry._delayInfo.push(kind);
  34611. }
  34612. // Bounding info
  34613. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34614. return geometry;
  34615. };
  34616. /**
  34617. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34618. * @return a JSON representation of the current geometry data (without the vertices data)
  34619. */
  34620. Geometry.prototype.serialize = function () {
  34621. var serializationObject = {};
  34622. serializationObject.id = this.id;
  34623. serializationObject.updatable = this._updatable;
  34624. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34625. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34626. }
  34627. return serializationObject;
  34628. };
  34629. Geometry.prototype.toNumberArray = function (origin) {
  34630. if (Array.isArray(origin)) {
  34631. return origin;
  34632. }
  34633. else {
  34634. return Array.prototype.slice.call(origin);
  34635. }
  34636. };
  34637. /**
  34638. * Serialize all vertices data into a JSON oject
  34639. * @returns a JSON representation of the current geometry data
  34640. */
  34641. Geometry.prototype.serializeVerticeData = function () {
  34642. var serializationObject = this.serialize();
  34643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34644. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34645. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34646. serializationObject.positions._updatable = true;
  34647. }
  34648. }
  34649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34650. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34651. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34652. serializationObject.normals._updatable = true;
  34653. }
  34654. }
  34655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34656. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34657. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34658. serializationObject.tangets._updatable = true;
  34659. }
  34660. }
  34661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34662. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34663. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34664. serializationObject.uvs._updatable = true;
  34665. }
  34666. }
  34667. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34668. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34669. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34670. serializationObject.uv2s._updatable = true;
  34671. }
  34672. }
  34673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34674. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34675. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34676. serializationObject.uv3s._updatable = true;
  34677. }
  34678. }
  34679. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34680. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34681. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34682. serializationObject.uv4s._updatable = true;
  34683. }
  34684. }
  34685. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34686. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34687. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34688. serializationObject.uv5s._updatable = true;
  34689. }
  34690. }
  34691. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34692. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34693. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34694. serializationObject.uv6s._updatable = true;
  34695. }
  34696. }
  34697. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34698. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34699. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34700. serializationObject.colors._updatable = true;
  34701. }
  34702. }
  34703. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34704. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34705. serializationObject.matricesIndices._isExpanded = true;
  34706. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34707. serializationObject.matricesIndices._updatable = true;
  34708. }
  34709. }
  34710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34711. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34712. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34713. serializationObject.matricesWeights._updatable = true;
  34714. }
  34715. }
  34716. serializationObject.indices = this.toNumberArray(this.getIndices());
  34717. return serializationObject;
  34718. };
  34719. // Statics
  34720. /**
  34721. * Extracts a clone of a mesh geometry
  34722. * @param mesh defines the source mesh
  34723. * @param id defines the unique ID of the new geometry object
  34724. * @returns the new geometry object
  34725. */
  34726. Geometry.ExtractFromMesh = function (mesh, id) {
  34727. var geometry = mesh._geometry;
  34728. if (!geometry) {
  34729. return null;
  34730. }
  34731. return geometry.copy(id);
  34732. };
  34733. /**
  34734. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34735. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34736. * Be aware Math.random() could cause collisions, but:
  34737. * "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"
  34738. * @returns a string containing a new GUID
  34739. */
  34740. Geometry.RandomId = function () {
  34741. return BABYLON.Tools.RandomId();
  34742. };
  34743. /** @ignore */
  34744. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34745. var scene = mesh.getScene();
  34746. // Geometry
  34747. var geometryId = parsedGeometry.geometryId;
  34748. if (geometryId) {
  34749. var geometry = scene.getGeometryByID(geometryId);
  34750. if (geometry) {
  34751. geometry.applyToMesh(mesh);
  34752. }
  34753. }
  34754. else if (parsedGeometry instanceof ArrayBuffer) {
  34755. var binaryInfo = mesh._binaryInfo;
  34756. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34757. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34758. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34759. }
  34760. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34761. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34762. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34763. }
  34764. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34765. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34766. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34767. }
  34768. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34769. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34770. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34771. }
  34772. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34773. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34774. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34775. }
  34776. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34777. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34778. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34779. }
  34780. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34781. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34782. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34783. }
  34784. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34785. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34786. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34787. }
  34788. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34789. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34790. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34791. }
  34792. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34793. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34794. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34795. }
  34796. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34797. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34798. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34799. }
  34800. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34801. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34802. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34803. }
  34804. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34805. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34806. mesh.setIndices(indicesData, null);
  34807. }
  34808. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34809. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34810. mesh.subMeshes = [];
  34811. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34812. var materialIndex = subMeshesData[(i * 5) + 0];
  34813. var verticesStart = subMeshesData[(i * 5) + 1];
  34814. var verticesCount = subMeshesData[(i * 5) + 2];
  34815. var indexStart = subMeshesData[(i * 5) + 3];
  34816. var indexCount = subMeshesData[(i * 5) + 4];
  34817. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34818. }
  34819. }
  34820. }
  34821. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34822. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34823. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34824. if (parsedGeometry.tangents) {
  34825. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34826. }
  34827. if (parsedGeometry.uvs) {
  34828. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34829. }
  34830. if (parsedGeometry.uvs2) {
  34831. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34832. }
  34833. if (parsedGeometry.uvs3) {
  34834. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34835. }
  34836. if (parsedGeometry.uvs4) {
  34837. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34838. }
  34839. if (parsedGeometry.uvs5) {
  34840. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34841. }
  34842. if (parsedGeometry.uvs6) {
  34843. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34844. }
  34845. if (parsedGeometry.colors) {
  34846. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34847. }
  34848. if (parsedGeometry.matricesIndices) {
  34849. if (!parsedGeometry.matricesIndices._isExpanded) {
  34850. var floatIndices = [];
  34851. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34852. var matricesIndex = parsedGeometry.matricesIndices[i];
  34853. floatIndices.push(matricesIndex & 0x000000FF);
  34854. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34855. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34856. floatIndices.push(matricesIndex >> 24);
  34857. }
  34858. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34859. }
  34860. else {
  34861. delete parsedGeometry.matricesIndices._isExpanded;
  34862. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34863. }
  34864. }
  34865. if (parsedGeometry.matricesIndicesExtra) {
  34866. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34867. var floatIndices = [];
  34868. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34869. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34870. floatIndices.push(matricesIndex & 0x000000FF);
  34871. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34872. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34873. floatIndices.push(matricesIndex >> 24);
  34874. }
  34875. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34876. }
  34877. else {
  34878. delete parsedGeometry.matricesIndices._isExpanded;
  34879. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34880. }
  34881. }
  34882. if (parsedGeometry.matricesWeights) {
  34883. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34885. }
  34886. if (parsedGeometry.matricesWeightsExtra) {
  34887. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34888. }
  34889. mesh.setIndices(parsedGeometry.indices, null);
  34890. }
  34891. // SubMeshes
  34892. if (parsedGeometry.subMeshes) {
  34893. mesh.subMeshes = [];
  34894. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34895. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34896. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34897. }
  34898. }
  34899. // Flat shading
  34900. if (mesh._shouldGenerateFlatShading) {
  34901. mesh.convertToFlatShadedMesh();
  34902. delete mesh._shouldGenerateFlatShading;
  34903. }
  34904. // Update
  34905. mesh.computeWorldMatrix(true);
  34906. // Octree
  34907. var sceneOctree = scene.selectionOctree;
  34908. if (sceneOctree !== undefined && sceneOctree !== null) {
  34909. sceneOctree.addMesh(mesh);
  34910. }
  34911. };
  34912. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  34913. var epsilon = 1e-3;
  34914. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  34915. return;
  34916. }
  34917. var noInfluenceBoneIndex = 0.0;
  34918. if (parsedGeometry.skeletonId > -1) {
  34919. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  34920. if (!skeleton) {
  34921. return;
  34922. }
  34923. noInfluenceBoneIndex = skeleton.bones.length;
  34924. }
  34925. else {
  34926. return;
  34927. }
  34928. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34929. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34930. var matricesWeights = parsedGeometry.matricesWeights;
  34931. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  34932. var influencers = parsedGeometry.numBoneInfluencer;
  34933. var size = matricesWeights.length;
  34934. for (var i = 0; i < size; i += 4) {
  34935. var weight = 0.0;
  34936. var firstZeroWeight = -1;
  34937. for (var j = 0; j < 4; j++) {
  34938. var w = matricesWeights[i + j];
  34939. weight += w;
  34940. if (w < epsilon && firstZeroWeight < 0) {
  34941. firstZeroWeight = j;
  34942. }
  34943. }
  34944. if (matricesWeightsExtra) {
  34945. for (var j = 0; j < 4; j++) {
  34946. var w = matricesWeightsExtra[i + j];
  34947. weight += w;
  34948. if (w < epsilon && firstZeroWeight < 0) {
  34949. firstZeroWeight = j + 4;
  34950. }
  34951. }
  34952. }
  34953. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  34954. firstZeroWeight = influencers - 1;
  34955. }
  34956. if (weight > epsilon) {
  34957. var mweight = 1.0 / weight;
  34958. for (var j = 0; j < 4; j++) {
  34959. matricesWeights[i + j] *= mweight;
  34960. }
  34961. if (matricesWeightsExtra) {
  34962. for (var j = 0; j < 4; j++) {
  34963. matricesWeightsExtra[i + j] *= mweight;
  34964. }
  34965. }
  34966. }
  34967. else {
  34968. if (firstZeroWeight >= 4) {
  34969. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  34970. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  34971. }
  34972. else {
  34973. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  34974. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  34975. }
  34976. }
  34977. }
  34978. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  34979. if (parsedGeometry.matricesWeightsExtra) {
  34980. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  34981. }
  34982. };
  34983. /**
  34984. * Create a new geometry from persisted data (Using .babylon file format)
  34985. * @param parsedVertexData defines the persisted data
  34986. * @param scene defines the hosting scene
  34987. * @param rootUrl defines the root url to use to load assets (like delayed data)
  34988. * @returns the new geometry object
  34989. */
  34990. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34991. if (scene.getGeometryByID(parsedVertexData.id)) {
  34992. return null; // null since geometry could be something else than a box...
  34993. }
  34994. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  34995. if (BABYLON.Tags) {
  34996. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34997. }
  34998. if (parsedVertexData.delayLoadingFile) {
  34999. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35000. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35001. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35002. geometry._delayInfo = [];
  35003. if (parsedVertexData.hasUVs) {
  35004. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35005. }
  35006. if (parsedVertexData.hasUVs2) {
  35007. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35008. }
  35009. if (parsedVertexData.hasUVs3) {
  35010. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35011. }
  35012. if (parsedVertexData.hasUVs4) {
  35013. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35014. }
  35015. if (parsedVertexData.hasUVs5) {
  35016. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35017. }
  35018. if (parsedVertexData.hasUVs6) {
  35019. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35020. }
  35021. if (parsedVertexData.hasColors) {
  35022. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35023. }
  35024. if (parsedVertexData.hasMatricesIndices) {
  35025. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35026. }
  35027. if (parsedVertexData.hasMatricesWeights) {
  35028. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35029. }
  35030. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35031. }
  35032. else {
  35033. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35034. }
  35035. scene.pushGeometry(geometry, true);
  35036. return geometry;
  35037. };
  35038. return Geometry;
  35039. }());
  35040. BABYLON.Geometry = Geometry;
  35041. // Primitives
  35042. /// Abstract class
  35043. /**
  35044. * Abstract class used to provide common services for all typed geometries
  35045. */
  35046. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35047. __extends(_PrimitiveGeometry, _super);
  35048. /**
  35049. * Creates a new typed geometry
  35050. * @param id defines the unique ID of the geometry
  35051. * @param scene defines the hosting scene
  35052. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35053. * @param mesh defines the hosting mesh (can be null)
  35054. */
  35055. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35056. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35057. if (mesh === void 0) { mesh = null; }
  35058. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35059. _this._canBeRegenerated = _canBeRegenerated;
  35060. _this._beingRegenerated = true;
  35061. _this.regenerate();
  35062. _this._beingRegenerated = false;
  35063. return _this;
  35064. }
  35065. /**
  35066. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35067. * @returns true if the geometry can be regenerated
  35068. */
  35069. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35070. return this._canBeRegenerated;
  35071. };
  35072. /**
  35073. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35074. */
  35075. _PrimitiveGeometry.prototype.regenerate = function () {
  35076. if (!this._canBeRegenerated) {
  35077. return;
  35078. }
  35079. this._beingRegenerated = true;
  35080. this.setAllVerticesData(this._regenerateVertexData(), false);
  35081. this._beingRegenerated = false;
  35082. };
  35083. /**
  35084. * Clone the geometry
  35085. * @param id defines the unique ID of the new geometry
  35086. * @returns the new geometry
  35087. */
  35088. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35089. return _super.prototype.copy.call(this, id);
  35090. };
  35091. // overrides
  35092. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35093. if (!this._beingRegenerated) {
  35094. return;
  35095. }
  35096. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35097. };
  35098. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35099. if (!this._beingRegenerated) {
  35100. return;
  35101. }
  35102. _super.prototype.setVerticesData.call(this, kind, data, false);
  35103. };
  35104. // to override
  35105. /** @ignore */
  35106. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35107. throw new Error("Abstract method");
  35108. };
  35109. _PrimitiveGeometry.prototype.copy = function (id) {
  35110. throw new Error("Must be overriden in sub-classes.");
  35111. };
  35112. _PrimitiveGeometry.prototype.serialize = function () {
  35113. var serializationObject = _super.prototype.serialize.call(this);
  35114. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35115. return serializationObject;
  35116. };
  35117. return _PrimitiveGeometry;
  35118. }(Geometry));
  35119. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35120. /**
  35121. * Creates a ribbon geometry
  35122. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35123. */
  35124. var RibbonGeometry = /** @class */ (function (_super) {
  35125. __extends(RibbonGeometry, _super);
  35126. /**
  35127. * Creates a ribbon geometry
  35128. * @param id defines the unique ID of the geometry
  35129. * @param scene defines the hosting scene
  35130. * @param pathArray defines the array of paths to use
  35131. * @param closeArray defines if the last path and the first path must be joined
  35132. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35133. * @param offset defines the offset between points
  35134. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35135. * @param mesh defines the hosting mesh (can be null)
  35136. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35137. */
  35138. function RibbonGeometry(id, scene,
  35139. /**
  35140. * Defines the array of paths to use
  35141. */
  35142. pathArray,
  35143. /**
  35144. * Defines if the last and first points of each path in your pathArray must be joined
  35145. */
  35146. closeArray,
  35147. /**
  35148. * Defines if the last and first points of each path in your pathArray must be joined
  35149. */
  35150. closePath,
  35151. /**
  35152. * Defines the offset between points
  35153. */
  35154. offset, canBeRegenerated, mesh,
  35155. /**
  35156. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35157. */
  35158. side) {
  35159. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35161. _this.pathArray = pathArray;
  35162. _this.closeArray = closeArray;
  35163. _this.closePath = closePath;
  35164. _this.offset = offset;
  35165. _this.side = side;
  35166. return _this;
  35167. }
  35168. /** @ignore */
  35169. RibbonGeometry.prototype._regenerateVertexData = function () {
  35170. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35171. };
  35172. RibbonGeometry.prototype.copy = function (id) {
  35173. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35174. };
  35175. return RibbonGeometry;
  35176. }(_PrimitiveGeometry));
  35177. BABYLON.RibbonGeometry = RibbonGeometry;
  35178. /**
  35179. * Creates a box geometry
  35180. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35181. */
  35182. var BoxGeometry = /** @class */ (function (_super) {
  35183. __extends(BoxGeometry, _super);
  35184. /**
  35185. * Creates a box geometry
  35186. * @param id defines the unique ID of the geometry
  35187. * @param scene defines the hosting scene
  35188. * @param size defines the zise of the box (width, height and depth are the same)
  35189. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35190. * @param mesh defines the hosting mesh (can be null)
  35191. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35192. */
  35193. function BoxGeometry(id, scene,
  35194. /**
  35195. * Defines the zise of the box (width, height and depth are the same)
  35196. */
  35197. size, canBeRegenerated, mesh,
  35198. /**
  35199. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35200. */
  35201. side) {
  35202. if (mesh === void 0) { mesh = null; }
  35203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35204. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35205. _this.size = size;
  35206. _this.side = side;
  35207. return _this;
  35208. }
  35209. BoxGeometry.prototype._regenerateVertexData = function () {
  35210. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35211. };
  35212. BoxGeometry.prototype.copy = function (id) {
  35213. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35214. };
  35215. BoxGeometry.prototype.serialize = function () {
  35216. var serializationObject = _super.prototype.serialize.call(this);
  35217. serializationObject.size = this.size;
  35218. return serializationObject;
  35219. };
  35220. BoxGeometry.Parse = function (parsedBox, scene) {
  35221. if (scene.getGeometryByID(parsedBox.id)) {
  35222. return null; // null since geometry could be something else than a box...
  35223. }
  35224. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35225. if (BABYLON.Tags) {
  35226. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35227. }
  35228. scene.pushGeometry(box, true);
  35229. return box;
  35230. };
  35231. return BoxGeometry;
  35232. }(_PrimitiveGeometry));
  35233. BABYLON.BoxGeometry = BoxGeometry;
  35234. /**
  35235. * Creates a sphere geometry
  35236. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35237. */
  35238. var SphereGeometry = /** @class */ (function (_super) {
  35239. __extends(SphereGeometry, _super);
  35240. /**
  35241. * Create a new sphere geometry
  35242. * @param id defines the unique ID of the geometry
  35243. * @param scene defines the hosting scene
  35244. * @param segments defines the number of segments to use to create the sphere
  35245. * @param diameter defines the diameter of the sphere
  35246. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35247. * @param mesh defines the hosting mesh (can be null)
  35248. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35249. */
  35250. function SphereGeometry(id, scene,
  35251. /**
  35252. * Defines the number of segments to use to create the sphere
  35253. */
  35254. segments,
  35255. /**
  35256. * Defines the diameter of the sphere
  35257. */
  35258. diameter, canBeRegenerated, mesh,
  35259. /**
  35260. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35261. */
  35262. side) {
  35263. if (mesh === void 0) { mesh = null; }
  35264. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35265. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35266. _this.segments = segments;
  35267. _this.diameter = diameter;
  35268. _this.side = side;
  35269. return _this;
  35270. }
  35271. SphereGeometry.prototype._regenerateVertexData = function () {
  35272. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35273. };
  35274. SphereGeometry.prototype.copy = function (id) {
  35275. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35276. };
  35277. SphereGeometry.prototype.serialize = function () {
  35278. var serializationObject = _super.prototype.serialize.call(this);
  35279. serializationObject.segments = this.segments;
  35280. serializationObject.diameter = this.diameter;
  35281. return serializationObject;
  35282. };
  35283. SphereGeometry.Parse = function (parsedSphere, scene) {
  35284. if (scene.getGeometryByID(parsedSphere.id)) {
  35285. return null; // null since geometry could be something else than a sphere...
  35286. }
  35287. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35288. if (BABYLON.Tags) {
  35289. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35290. }
  35291. scene.pushGeometry(sphere, true);
  35292. return sphere;
  35293. };
  35294. return SphereGeometry;
  35295. }(_PrimitiveGeometry));
  35296. BABYLON.SphereGeometry = SphereGeometry;
  35297. /**
  35298. * Creates a disc geometry
  35299. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35300. */
  35301. var DiscGeometry = /** @class */ (function (_super) {
  35302. __extends(DiscGeometry, _super);
  35303. /**
  35304. * Creates a new disc geometry
  35305. * @param id defines the unique ID of the geometry
  35306. * @param scene defines the hosting scene
  35307. * @param radius defines the radius of the disc
  35308. * @param tessellation defines the tesselation factor to apply to the disc
  35309. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35310. * @param mesh defines the hosting mesh (can be null)
  35311. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35312. */
  35313. function DiscGeometry(id, scene,
  35314. /**
  35315. * Defines the radius of the disc
  35316. */
  35317. radius,
  35318. /**
  35319. * Defines the tesselation factor to apply to the disc
  35320. */
  35321. tessellation, canBeRegenerated, mesh,
  35322. /**
  35323. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35324. */
  35325. side) {
  35326. if (mesh === void 0) { mesh = null; }
  35327. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35328. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35329. _this.radius = radius;
  35330. _this.tessellation = tessellation;
  35331. _this.side = side;
  35332. return _this;
  35333. }
  35334. DiscGeometry.prototype._regenerateVertexData = function () {
  35335. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35336. };
  35337. DiscGeometry.prototype.copy = function (id) {
  35338. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35339. };
  35340. return DiscGeometry;
  35341. }(_PrimitiveGeometry));
  35342. BABYLON.DiscGeometry = DiscGeometry;
  35343. /**
  35344. * Creates a new cylinder geometry
  35345. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35346. */
  35347. var CylinderGeometry = /** @class */ (function (_super) {
  35348. __extends(CylinderGeometry, _super);
  35349. /**
  35350. * Creates a new cylinder geometry
  35351. * @param id defines the unique ID of the geometry
  35352. * @param scene defines the hosting scene
  35353. * @param height defines the height of the cylinder
  35354. * @param diameterTop defines the diameter of the cylinder's top cap
  35355. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35356. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35357. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35358. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35359. * @param mesh defines the hosting mesh (can be null)
  35360. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35361. */
  35362. function CylinderGeometry(id, scene,
  35363. /**
  35364. * Defines the height of the cylinder
  35365. */
  35366. height,
  35367. /**
  35368. * Defines the diameter of the cylinder's top cap
  35369. */
  35370. diameterTop,
  35371. /**
  35372. * Defines the diameter of the cylinder's bottom cap
  35373. */
  35374. diameterBottom,
  35375. /**
  35376. * Defines the tessellation factor to apply to the cylinder
  35377. */
  35378. tessellation,
  35379. /**
  35380. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35381. */
  35382. subdivisions, canBeRegenerated, mesh,
  35383. /**
  35384. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35385. */
  35386. side) {
  35387. if (subdivisions === void 0) { subdivisions = 1; }
  35388. if (mesh === void 0) { mesh = null; }
  35389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35390. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35391. _this.height = height;
  35392. _this.diameterTop = diameterTop;
  35393. _this.diameterBottom = diameterBottom;
  35394. _this.tessellation = tessellation;
  35395. _this.subdivisions = subdivisions;
  35396. _this.side = side;
  35397. return _this;
  35398. }
  35399. CylinderGeometry.prototype._regenerateVertexData = function () {
  35400. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35401. };
  35402. CylinderGeometry.prototype.copy = function (id) {
  35403. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35404. };
  35405. CylinderGeometry.prototype.serialize = function () {
  35406. var serializationObject = _super.prototype.serialize.call(this);
  35407. serializationObject.height = this.height;
  35408. serializationObject.diameterTop = this.diameterTop;
  35409. serializationObject.diameterBottom = this.diameterBottom;
  35410. serializationObject.tessellation = this.tessellation;
  35411. return serializationObject;
  35412. };
  35413. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35414. if (scene.getGeometryByID(parsedCylinder.id)) {
  35415. return null; // null since geometry could be something else than a cylinder...
  35416. }
  35417. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35418. if (BABYLON.Tags) {
  35419. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35420. }
  35421. scene.pushGeometry(cylinder, true);
  35422. return cylinder;
  35423. };
  35424. return CylinderGeometry;
  35425. }(_PrimitiveGeometry));
  35426. BABYLON.CylinderGeometry = CylinderGeometry;
  35427. /**
  35428. * Creates a new torus geometry
  35429. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35430. */
  35431. var TorusGeometry = /** @class */ (function (_super) {
  35432. __extends(TorusGeometry, _super);
  35433. /**
  35434. * Creates a new torus geometry
  35435. * @param id defines the unique ID of the geometry
  35436. * @param scene defines the hosting scene
  35437. * @param diameter defines the diameter of the torus
  35438. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35439. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35440. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35441. * @param mesh defines the hosting mesh (can be null)
  35442. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35443. */
  35444. function TorusGeometry(id, scene,
  35445. /**
  35446. * Defines the diameter of the torus
  35447. */
  35448. diameter,
  35449. /**
  35450. * Defines the thickness of the torus (ie. internal diameter)
  35451. */
  35452. thickness,
  35453. /**
  35454. * Defines the tesselation factor to apply to the torus
  35455. */
  35456. tessellation, canBeRegenerated, mesh,
  35457. /**
  35458. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35459. */
  35460. side) {
  35461. if (mesh === void 0) { mesh = null; }
  35462. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35463. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35464. _this.diameter = diameter;
  35465. _this.thickness = thickness;
  35466. _this.tessellation = tessellation;
  35467. _this.side = side;
  35468. return _this;
  35469. }
  35470. TorusGeometry.prototype._regenerateVertexData = function () {
  35471. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35472. };
  35473. TorusGeometry.prototype.copy = function (id) {
  35474. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35475. };
  35476. TorusGeometry.prototype.serialize = function () {
  35477. var serializationObject = _super.prototype.serialize.call(this);
  35478. serializationObject.diameter = this.diameter;
  35479. serializationObject.thickness = this.thickness;
  35480. serializationObject.tessellation = this.tessellation;
  35481. return serializationObject;
  35482. };
  35483. TorusGeometry.Parse = function (parsedTorus, scene) {
  35484. if (scene.getGeometryByID(parsedTorus.id)) {
  35485. return null; // null since geometry could be something else than a torus...
  35486. }
  35487. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35488. if (BABYLON.Tags) {
  35489. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35490. }
  35491. scene.pushGeometry(torus, true);
  35492. return torus;
  35493. };
  35494. return TorusGeometry;
  35495. }(_PrimitiveGeometry));
  35496. BABYLON.TorusGeometry = TorusGeometry;
  35497. /**
  35498. * Creates a new ground geometry
  35499. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35500. */
  35501. var GroundGeometry = /** @class */ (function (_super) {
  35502. __extends(GroundGeometry, _super);
  35503. /**
  35504. * Creates a new ground geometry
  35505. * @param id defines the unique ID of the geometry
  35506. * @param scene defines the hosting scene
  35507. * @param width defines the width of the ground
  35508. * @param height defines the height of the ground
  35509. * @param subdivisions defines the subdivisions to apply to the ground
  35510. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35511. * @param mesh defines the hosting mesh (can be null)
  35512. */
  35513. function GroundGeometry(id, scene,
  35514. /**
  35515. * Defines the width of the ground
  35516. */
  35517. width,
  35518. /**
  35519. * Defines the height of the ground
  35520. */
  35521. height,
  35522. /**
  35523. * Defines the subdivisions to apply to the ground
  35524. */
  35525. subdivisions, canBeRegenerated, mesh) {
  35526. if (mesh === void 0) { mesh = null; }
  35527. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35528. _this.width = width;
  35529. _this.height = height;
  35530. _this.subdivisions = subdivisions;
  35531. return _this;
  35532. }
  35533. GroundGeometry.prototype._regenerateVertexData = function () {
  35534. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35535. };
  35536. GroundGeometry.prototype.copy = function (id) {
  35537. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35538. };
  35539. GroundGeometry.prototype.serialize = function () {
  35540. var serializationObject = _super.prototype.serialize.call(this);
  35541. serializationObject.width = this.width;
  35542. serializationObject.height = this.height;
  35543. serializationObject.subdivisions = this.subdivisions;
  35544. return serializationObject;
  35545. };
  35546. GroundGeometry.Parse = function (parsedGround, scene) {
  35547. if (scene.getGeometryByID(parsedGround.id)) {
  35548. return null; // null since geometry could be something else than a ground...
  35549. }
  35550. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35551. if (BABYLON.Tags) {
  35552. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35553. }
  35554. scene.pushGeometry(ground, true);
  35555. return ground;
  35556. };
  35557. return GroundGeometry;
  35558. }(_PrimitiveGeometry));
  35559. BABYLON.GroundGeometry = GroundGeometry;
  35560. /**
  35561. * Creates a tiled ground geometry
  35562. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35563. */
  35564. var TiledGroundGeometry = /** @class */ (function (_super) {
  35565. __extends(TiledGroundGeometry, _super);
  35566. /**
  35567. * Creates a tiled ground geometry
  35568. * @param id defines the unique ID of the geometry
  35569. * @param scene defines the hosting scene
  35570. * @param xmin defines the minimum value on X axis
  35571. * @param zmin defines the minimum value on Z axis
  35572. * @param xmax defines the maximum value on X axis
  35573. * @param zmax defines the maximum value on Z axis
  35574. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35575. * @param precision defines the precision to use when computing the tiles
  35576. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35577. * @param mesh defines the hosting mesh (can be null)
  35578. */
  35579. function TiledGroundGeometry(id, scene,
  35580. /**
  35581. * Defines the minimum value on X axis
  35582. */
  35583. xmin,
  35584. /**
  35585. * Defines the minimum value on Z axis
  35586. */
  35587. zmin,
  35588. /**
  35589. * Defines the maximum value on X axis
  35590. */
  35591. xmax,
  35592. /**
  35593. * Defines the maximum value on Z axis
  35594. */
  35595. zmax,
  35596. /**
  35597. * Defines the subdivisions to apply to the ground
  35598. */
  35599. subdivisions,
  35600. /**
  35601. * Defines the precision to use when computing the tiles
  35602. */
  35603. precision, canBeRegenerated, mesh) {
  35604. if (mesh === void 0) { mesh = null; }
  35605. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35606. _this.xmin = xmin;
  35607. _this.zmin = zmin;
  35608. _this.xmax = xmax;
  35609. _this.zmax = zmax;
  35610. _this.subdivisions = subdivisions;
  35611. _this.precision = precision;
  35612. return _this;
  35613. }
  35614. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35615. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35616. };
  35617. TiledGroundGeometry.prototype.copy = function (id) {
  35618. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35619. };
  35620. return TiledGroundGeometry;
  35621. }(_PrimitiveGeometry));
  35622. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35623. /**
  35624. * Creates a plane geometry
  35625. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35626. */
  35627. var PlaneGeometry = /** @class */ (function (_super) {
  35628. __extends(PlaneGeometry, _super);
  35629. /**
  35630. * Creates a plane geometry
  35631. * @param id defines the unique ID of the geometry
  35632. * @param scene defines the hosting scene
  35633. * @param size defines the size of the plane (width === height)
  35634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35635. * @param mesh defines the hosting mesh (can be null)
  35636. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35637. */
  35638. function PlaneGeometry(id, scene,
  35639. /**
  35640. * Defines the size of the plane (width === height)
  35641. */
  35642. size, canBeRegenerated, mesh,
  35643. /**
  35644. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35645. */
  35646. side) {
  35647. if (mesh === void 0) { mesh = null; }
  35648. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35649. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35650. _this.size = size;
  35651. _this.side = side;
  35652. return _this;
  35653. }
  35654. PlaneGeometry.prototype._regenerateVertexData = function () {
  35655. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35656. };
  35657. PlaneGeometry.prototype.copy = function (id) {
  35658. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35659. };
  35660. PlaneGeometry.prototype.serialize = function () {
  35661. var serializationObject = _super.prototype.serialize.call(this);
  35662. serializationObject.size = this.size;
  35663. return serializationObject;
  35664. };
  35665. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35666. if (scene.getGeometryByID(parsedPlane.id)) {
  35667. return null; // null since geometry could be something else than a ground...
  35668. }
  35669. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35670. if (BABYLON.Tags) {
  35671. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35672. }
  35673. scene.pushGeometry(plane, true);
  35674. return plane;
  35675. };
  35676. return PlaneGeometry;
  35677. }(_PrimitiveGeometry));
  35678. BABYLON.PlaneGeometry = PlaneGeometry;
  35679. /**
  35680. * Creates a torus knot geometry
  35681. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35682. */
  35683. var TorusKnotGeometry = /** @class */ (function (_super) {
  35684. __extends(TorusKnotGeometry, _super);
  35685. /**
  35686. * Creates a torus knot geometry
  35687. * @param id defines the unique ID of the geometry
  35688. * @param scene defines the hosting scene
  35689. * @param radius defines the radius of the torus knot
  35690. * @param tube defines the thickness of the torus knot tube
  35691. * @param radialSegments defines the number of radial segments
  35692. * @param tubularSegments defines the number of tubular segments
  35693. * @param p defines the first number of windings
  35694. * @param q defines the second number of windings
  35695. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35696. * @param mesh defines the hosting mesh (can be null)
  35697. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35698. */
  35699. function TorusKnotGeometry(id, scene,
  35700. /**
  35701. * Defines the radius of the torus knot
  35702. */
  35703. radius,
  35704. /**
  35705. * Defines the thickness of the torus knot tube
  35706. */
  35707. tube,
  35708. /**
  35709. * Defines the number of radial segments
  35710. */
  35711. radialSegments,
  35712. /**
  35713. * Defines the number of tubular segments
  35714. */
  35715. tubularSegments,
  35716. /**
  35717. * Defines the first number of windings
  35718. */
  35719. p,
  35720. /**
  35721. * Defines the second number of windings
  35722. */
  35723. q, canBeRegenerated, mesh,
  35724. /**
  35725. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35726. */
  35727. side) {
  35728. if (mesh === void 0) { mesh = null; }
  35729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35731. _this.radius = radius;
  35732. _this.tube = tube;
  35733. _this.radialSegments = radialSegments;
  35734. _this.tubularSegments = tubularSegments;
  35735. _this.p = p;
  35736. _this.q = q;
  35737. _this.side = side;
  35738. return _this;
  35739. }
  35740. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35741. 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 });
  35742. };
  35743. TorusKnotGeometry.prototype.copy = function (id) {
  35744. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35745. };
  35746. TorusKnotGeometry.prototype.serialize = function () {
  35747. var serializationObject = _super.prototype.serialize.call(this);
  35748. serializationObject.radius = this.radius;
  35749. serializationObject.tube = this.tube;
  35750. serializationObject.radialSegments = this.radialSegments;
  35751. serializationObject.tubularSegments = this.tubularSegments;
  35752. serializationObject.p = this.p;
  35753. serializationObject.q = this.q;
  35754. return serializationObject;
  35755. };
  35756. ;
  35757. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35758. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35759. return null; // null since geometry could be something else than a ground...
  35760. }
  35761. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35762. if (BABYLON.Tags) {
  35763. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35764. }
  35765. scene.pushGeometry(torusKnot, true);
  35766. return torusKnot;
  35767. };
  35768. return TorusKnotGeometry;
  35769. }(_PrimitiveGeometry));
  35770. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35771. //}
  35772. })(BABYLON || (BABYLON = {}));
  35773. //# sourceMappingURL=babylon.geometry.js.map
  35774. var BABYLON;
  35775. (function (BABYLON) {
  35776. /**
  35777. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35778. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35779. */
  35780. var PostProcessManager = /** @class */ (function () {
  35781. /**
  35782. * Creates a new instance of @see PostProcess
  35783. * @param scene The scene that the post process is associated with.
  35784. */
  35785. function PostProcessManager(scene) {
  35786. this._vertexBuffers = {};
  35787. this._scene = scene;
  35788. }
  35789. PostProcessManager.prototype._prepareBuffers = function () {
  35790. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35791. return;
  35792. }
  35793. // VBO
  35794. var vertices = [];
  35795. vertices.push(1, 1);
  35796. vertices.push(-1, 1);
  35797. vertices.push(-1, -1);
  35798. vertices.push(1, -1);
  35799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35800. this._buildIndexBuffer();
  35801. };
  35802. PostProcessManager.prototype._buildIndexBuffer = function () {
  35803. // Indices
  35804. var indices = [];
  35805. indices.push(0);
  35806. indices.push(1);
  35807. indices.push(2);
  35808. indices.push(0);
  35809. indices.push(2);
  35810. indices.push(3);
  35811. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35812. };
  35813. /**
  35814. * Rebuilds the vertex buffers of the manager.
  35815. */
  35816. PostProcessManager.prototype._rebuild = function () {
  35817. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35818. if (!vb) {
  35819. return;
  35820. }
  35821. vb._rebuild();
  35822. this._buildIndexBuffer();
  35823. };
  35824. // Methods
  35825. /**
  35826. * Prepares a frame to be run through a post process.
  35827. * @param sourceTexture The input texture to the post procesess. (default: null)
  35828. * @param postProcesses An array of post processes to be run. (default: null)
  35829. * @returns True if the post processes were able to be run.
  35830. */
  35831. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35832. if (sourceTexture === void 0) { sourceTexture = null; }
  35833. if (postProcesses === void 0) { postProcesses = null; }
  35834. var camera = this._scene.activeCamera;
  35835. if (!camera) {
  35836. return false;
  35837. }
  35838. var postProcesses = postProcesses || camera._postProcesses;
  35839. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35840. return false;
  35841. }
  35842. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35843. return true;
  35844. };
  35845. /**
  35846. * Manually render a set of post processes to a texture.
  35847. * @param postProcesses An array of post processes to be run.
  35848. * @param targetTexture The target texture to render to.
  35849. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35850. */
  35851. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35852. if (targetTexture === void 0) { targetTexture = null; }
  35853. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35854. var engine = this._scene.getEngine();
  35855. for (var index = 0; index < postProcesses.length; index++) {
  35856. if (index < postProcesses.length - 1) {
  35857. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35858. }
  35859. else {
  35860. if (targetTexture) {
  35861. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35862. }
  35863. else {
  35864. engine.restoreDefaultFramebuffer();
  35865. }
  35866. }
  35867. var pp = postProcesses[index];
  35868. var effect = pp.apply();
  35869. if (effect) {
  35870. pp.onBeforeRenderObservable.notifyObservers(effect);
  35871. // VBOs
  35872. this._prepareBuffers();
  35873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35874. // Draw order
  35875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35876. pp.onAfterRenderObservable.notifyObservers(effect);
  35877. }
  35878. }
  35879. // Restore depth buffer
  35880. engine.setDepthBuffer(true);
  35881. engine.setDepthWrite(true);
  35882. };
  35883. /**
  35884. * Finalize the result of the output of the postprocesses.
  35885. * @param doNotPresent If true the result will not be displayed to the screen.
  35886. * @param targetTexture The target texture to render to.
  35887. * @param faceIndex The index of the face to bind the target texture to.
  35888. * @param postProcesses The array of post processes to render.
  35889. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  35890. */
  35891. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  35892. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35893. var camera = this._scene.activeCamera;
  35894. if (!camera) {
  35895. return;
  35896. }
  35897. postProcesses = postProcesses || camera._postProcesses;
  35898. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35899. return;
  35900. }
  35901. var engine = this._scene.getEngine();
  35902. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35903. if (index < len - 1) {
  35904. postProcesses[index + 1].activate(camera, targetTexture);
  35905. }
  35906. else {
  35907. if (targetTexture) {
  35908. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  35909. }
  35910. else {
  35911. engine.restoreDefaultFramebuffer();
  35912. }
  35913. }
  35914. if (doNotPresent) {
  35915. break;
  35916. }
  35917. var pp = postProcesses[index];
  35918. var effect = pp.apply();
  35919. if (effect) {
  35920. pp.onBeforeRenderObservable.notifyObservers(effect);
  35921. // VBOs
  35922. this._prepareBuffers();
  35923. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35924. // Draw order
  35925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35926. pp.onAfterRenderObservable.notifyObservers(effect);
  35927. }
  35928. }
  35929. // Restore states
  35930. engine.setDepthBuffer(true);
  35931. engine.setDepthWrite(true);
  35932. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35933. };
  35934. /**
  35935. * Disposes of the post process manager.
  35936. */
  35937. PostProcessManager.prototype.dispose = function () {
  35938. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35939. if (buffer) {
  35940. buffer.dispose();
  35941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35942. }
  35943. if (this._indexBuffer) {
  35944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35945. this._indexBuffer = null;
  35946. }
  35947. };
  35948. return PostProcessManager;
  35949. }());
  35950. BABYLON.PostProcessManager = PostProcessManager;
  35951. })(BABYLON || (BABYLON = {}));
  35952. //# sourceMappingURL=babylon.postProcessManager.js.map
  35953. var BABYLON;
  35954. (function (BABYLON) {
  35955. /**
  35956. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  35957. */
  35958. var PerformanceMonitor = /** @class */ (function () {
  35959. /**
  35960. * constructor
  35961. * @param frameSampleSize The number of samples required to saturate the sliding window
  35962. */
  35963. function PerformanceMonitor(frameSampleSize) {
  35964. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  35965. this._enabled = true;
  35966. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  35967. }
  35968. /**
  35969. * Samples current frame
  35970. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  35971. */
  35972. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  35973. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  35974. if (!this._enabled)
  35975. return;
  35976. if (this._lastFrameTimeMs != null) {
  35977. var dt = timeMs - this._lastFrameTimeMs;
  35978. this._rollingFrameTime.add(dt);
  35979. }
  35980. this._lastFrameTimeMs = timeMs;
  35981. };
  35982. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  35983. /**
  35984. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35985. * @return Average frame time in milliseconds
  35986. */
  35987. get: function () {
  35988. return this._rollingFrameTime.average;
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  35994. /**
  35995. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35996. * @return Frame time variance in milliseconds squared
  35997. */
  35998. get: function () {
  35999. return this._rollingFrameTime.variance;
  36000. },
  36001. enumerable: true,
  36002. configurable: true
  36003. });
  36004. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36005. /**
  36006. * Returns the frame time of the most recent frame
  36007. * @return Frame time in milliseconds
  36008. */
  36009. get: function () {
  36010. return this._rollingFrameTime.history(0);
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36016. /**
  36017. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36018. * @return Framerate in frames per second
  36019. */
  36020. get: function () {
  36021. return 1000.0 / this._rollingFrameTime.average;
  36022. },
  36023. enumerable: true,
  36024. configurable: true
  36025. });
  36026. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36027. /**
  36028. * Returns the average framerate in frames per second using the most recent frame time
  36029. * @return Framerate in frames per second
  36030. */
  36031. get: function () {
  36032. var history = this._rollingFrameTime.history(0);
  36033. if (history === 0) {
  36034. return 0;
  36035. }
  36036. return 1000.0 / history;
  36037. },
  36038. enumerable: true,
  36039. configurable: true
  36040. });
  36041. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36042. /**
  36043. * Returns true if enough samples have been taken to completely fill the sliding window
  36044. * @return true if saturated
  36045. */
  36046. get: function () {
  36047. return this._rollingFrameTime.isSaturated();
  36048. },
  36049. enumerable: true,
  36050. configurable: true
  36051. });
  36052. /**
  36053. * Enables contributions to the sliding window sample set
  36054. */
  36055. PerformanceMonitor.prototype.enable = function () {
  36056. this._enabled = true;
  36057. };
  36058. /**
  36059. * Disables contributions to the sliding window sample set
  36060. * Samples will not be interpolated over the disabled period
  36061. */
  36062. PerformanceMonitor.prototype.disable = function () {
  36063. this._enabled = false;
  36064. //clear last sample to avoid interpolating over the disabled period when next enabled
  36065. this._lastFrameTimeMs = null;
  36066. };
  36067. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36068. /**
  36069. * Returns true if sampling is enabled
  36070. * @return true if enabled
  36071. */
  36072. get: function () {
  36073. return this._enabled;
  36074. },
  36075. enumerable: true,
  36076. configurable: true
  36077. });
  36078. /**
  36079. * Resets performance monitor
  36080. */
  36081. PerformanceMonitor.prototype.reset = function () {
  36082. //clear last sample to avoid interpolating over the disabled period when next enabled
  36083. this._lastFrameTimeMs = null;
  36084. //wipe record
  36085. this._rollingFrameTime.reset();
  36086. };
  36087. return PerformanceMonitor;
  36088. }());
  36089. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36090. /**
  36091. * RollingAverage
  36092. *
  36093. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36094. */
  36095. var RollingAverage = /** @class */ (function () {
  36096. /**
  36097. * constructor
  36098. * @param length The number of samples required to saturate the sliding window
  36099. */
  36100. function RollingAverage(length) {
  36101. this._samples = new Array(length);
  36102. this.reset();
  36103. }
  36104. /**
  36105. * Adds a sample to the sample set
  36106. * @param v The sample value
  36107. */
  36108. RollingAverage.prototype.add = function (v) {
  36109. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36110. var delta;
  36111. //we need to check if we've already wrapped round
  36112. if (this.isSaturated()) {
  36113. //remove bottom of stack from mean
  36114. var bottomValue = this._samples[this._pos];
  36115. delta = bottomValue - this.average;
  36116. this.average -= delta / (this._sampleCount - 1);
  36117. this._m2 -= delta * (bottomValue - this.average);
  36118. }
  36119. else {
  36120. this._sampleCount++;
  36121. }
  36122. //add new value to mean
  36123. delta = v - this.average;
  36124. this.average += delta / (this._sampleCount);
  36125. this._m2 += delta * (v - this.average);
  36126. //set the new variance
  36127. this.variance = this._m2 / (this._sampleCount - 1);
  36128. this._samples[this._pos] = v;
  36129. this._pos++;
  36130. this._pos %= this._samples.length; //positive wrap around
  36131. };
  36132. /**
  36133. * Returns previously added values or null if outside of history or outside the sliding window domain
  36134. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36135. * @return Value previously recorded with add() or null if outside of range
  36136. */
  36137. RollingAverage.prototype.history = function (i) {
  36138. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36139. return 0;
  36140. }
  36141. var i0 = this._wrapPosition(this._pos - 1.0);
  36142. return this._samples[this._wrapPosition(i0 - i)];
  36143. };
  36144. /**
  36145. * Returns true if enough samples have been taken to completely fill the sliding window
  36146. * @return true if sample-set saturated
  36147. */
  36148. RollingAverage.prototype.isSaturated = function () {
  36149. return this._sampleCount >= this._samples.length;
  36150. };
  36151. /**
  36152. * Resets the rolling average (equivalent to 0 samples taken so far)
  36153. */
  36154. RollingAverage.prototype.reset = function () {
  36155. this.average = 0;
  36156. this.variance = 0;
  36157. this._sampleCount = 0;
  36158. this._pos = 0;
  36159. this._m2 = 0;
  36160. };
  36161. /**
  36162. * Wraps a value around the sample range boundaries
  36163. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36164. * @return Wrapped position in sample range
  36165. */
  36166. RollingAverage.prototype._wrapPosition = function (i) {
  36167. var max = this._samples.length;
  36168. return ((i % max) + max) % max;
  36169. };
  36170. return RollingAverage;
  36171. }());
  36172. BABYLON.RollingAverage = RollingAverage;
  36173. })(BABYLON || (BABYLON = {}));
  36174. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36175. var BABYLON;
  36176. (function (BABYLON) {
  36177. /**
  36178. * This groups together the common properties used for image processing either in direct forward pass
  36179. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36180. * or not.
  36181. */
  36182. var ImageProcessingConfiguration = /** @class */ (function () {
  36183. function ImageProcessingConfiguration() {
  36184. /**
  36185. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36186. */
  36187. this.colorCurves = new BABYLON.ColorCurves();
  36188. this._colorCurvesEnabled = false;
  36189. this._colorGradingEnabled = false;
  36190. this._colorGradingWithGreenDepth = true;
  36191. this._colorGradingBGR = true;
  36192. this._exposure = 1.0;
  36193. this._toneMappingEnabled = false;
  36194. this._contrast = 1.0;
  36195. /**
  36196. * Vignette stretch size.
  36197. */
  36198. this.vignetteStretch = 0;
  36199. /**
  36200. * Vignette centre X Offset.
  36201. */
  36202. this.vignetteCentreX = 0;
  36203. /**
  36204. * Vignette centre Y Offset.
  36205. */
  36206. this.vignetteCentreY = 0;
  36207. /**
  36208. * Vignette weight or intensity of the vignette effect.
  36209. */
  36210. this.vignetteWeight = 1.5;
  36211. /**
  36212. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36213. * if vignetteEnabled is set to true.
  36214. */
  36215. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36216. /**
  36217. * Camera field of view used by the Vignette effect.
  36218. */
  36219. this.vignetteCameraFov = 0.5;
  36220. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36221. this._vignetteEnabled = false;
  36222. this._applyByPostProcess = false;
  36223. this._isEnabled = true;
  36224. /**
  36225. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36226. * @type {BABYLON.Observable}
  36227. */
  36228. this.onUpdateParameters = new BABYLON.Observable();
  36229. }
  36230. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36231. /**
  36232. * Gets wether the color curves effect is enabled.
  36233. */
  36234. get: function () {
  36235. return this._colorCurvesEnabled;
  36236. },
  36237. /**
  36238. * Sets wether the color curves effect is enabled.
  36239. */
  36240. set: function (value) {
  36241. if (this._colorCurvesEnabled === value) {
  36242. return;
  36243. }
  36244. this._colorCurvesEnabled = value;
  36245. this._updateParameters();
  36246. },
  36247. enumerable: true,
  36248. configurable: true
  36249. });
  36250. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36251. /**
  36252. * Gets wether the color grading effect is enabled.
  36253. */
  36254. get: function () {
  36255. return this._colorGradingEnabled;
  36256. },
  36257. /**
  36258. * Sets wether the color grading effect is enabled.
  36259. */
  36260. set: function (value) {
  36261. if (this._colorGradingEnabled === value) {
  36262. return;
  36263. }
  36264. this._colorGradingEnabled = value;
  36265. this._updateParameters();
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36271. /**
  36272. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36273. */
  36274. get: function () {
  36275. return this._colorGradingWithGreenDepth;
  36276. },
  36277. /**
  36278. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36279. */
  36280. set: function (value) {
  36281. if (this._colorGradingWithGreenDepth === value) {
  36282. return;
  36283. }
  36284. this._colorGradingWithGreenDepth = value;
  36285. this._updateParameters();
  36286. },
  36287. enumerable: true,
  36288. configurable: true
  36289. });
  36290. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36291. /**
  36292. * Gets wether the color grading texture contains BGR values.
  36293. */
  36294. get: function () {
  36295. return this._colorGradingBGR;
  36296. },
  36297. /**
  36298. * Sets wether the color grading texture contains BGR values.
  36299. */
  36300. set: function (value) {
  36301. if (this._colorGradingBGR === value) {
  36302. return;
  36303. }
  36304. this._colorGradingBGR = value;
  36305. this._updateParameters();
  36306. },
  36307. enumerable: true,
  36308. configurable: true
  36309. });
  36310. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36311. /**
  36312. * Gets the Exposure used in the effect.
  36313. */
  36314. get: function () {
  36315. return this._exposure;
  36316. },
  36317. /**
  36318. * Sets the Exposure used in the effect.
  36319. */
  36320. set: function (value) {
  36321. if (this._exposure === value) {
  36322. return;
  36323. }
  36324. this._exposure = value;
  36325. this._updateParameters();
  36326. },
  36327. enumerable: true,
  36328. configurable: true
  36329. });
  36330. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36331. /**
  36332. * Gets wether the tone mapping effect is enabled.
  36333. */
  36334. get: function () {
  36335. return this._toneMappingEnabled;
  36336. },
  36337. /**
  36338. * Sets wether the tone mapping effect is enabled.
  36339. */
  36340. set: function (value) {
  36341. if (this._toneMappingEnabled === value) {
  36342. return;
  36343. }
  36344. this._toneMappingEnabled = value;
  36345. this._updateParameters();
  36346. },
  36347. enumerable: true,
  36348. configurable: true
  36349. });
  36350. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36351. /**
  36352. * Gets the contrast used in the effect.
  36353. */
  36354. get: function () {
  36355. return this._contrast;
  36356. },
  36357. /**
  36358. * Sets the contrast used in the effect.
  36359. */
  36360. set: function (value) {
  36361. if (this._contrast === value) {
  36362. return;
  36363. }
  36364. this._contrast = value;
  36365. this._updateParameters();
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36371. /**
  36372. * Gets the vignette blend mode allowing different kind of effect.
  36373. */
  36374. get: function () {
  36375. return this._vignetteBlendMode;
  36376. },
  36377. /**
  36378. * Sets the vignette blend mode allowing different kind of effect.
  36379. */
  36380. set: function (value) {
  36381. if (this._vignetteBlendMode === value) {
  36382. return;
  36383. }
  36384. this._vignetteBlendMode = value;
  36385. this._updateParameters();
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36391. /**
  36392. * Gets wether the vignette effect is enabled.
  36393. */
  36394. get: function () {
  36395. return this._vignetteEnabled;
  36396. },
  36397. /**
  36398. * Sets wether the vignette effect is enabled.
  36399. */
  36400. set: function (value) {
  36401. if (this._vignetteEnabled === value) {
  36402. return;
  36403. }
  36404. this._vignetteEnabled = value;
  36405. this._updateParameters();
  36406. },
  36407. enumerable: true,
  36408. configurable: true
  36409. });
  36410. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36411. /**
  36412. * Gets wether the image processing is applied through a post process or not.
  36413. */
  36414. get: function () {
  36415. return this._applyByPostProcess;
  36416. },
  36417. /**
  36418. * Sets wether the image processing is applied through a post process or not.
  36419. */
  36420. set: function (value) {
  36421. if (this._applyByPostProcess === value) {
  36422. return;
  36423. }
  36424. this._applyByPostProcess = value;
  36425. this._updateParameters();
  36426. },
  36427. enumerable: true,
  36428. configurable: true
  36429. });
  36430. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36431. /**
  36432. * Gets wether the image processing is enabled or not.
  36433. */
  36434. get: function () {
  36435. return this._isEnabled;
  36436. },
  36437. /**
  36438. * Sets wether the image processing is enabled or not.
  36439. */
  36440. set: function (value) {
  36441. if (this._isEnabled === value) {
  36442. return;
  36443. }
  36444. this._isEnabled = value;
  36445. this._updateParameters();
  36446. },
  36447. enumerable: true,
  36448. configurable: true
  36449. });
  36450. /**
  36451. * Method called each time the image processing information changes requires to recompile the effect.
  36452. */
  36453. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36454. this.onUpdateParameters.notifyObservers(this);
  36455. };
  36456. ImageProcessingConfiguration.prototype.getClassName = function () {
  36457. return "ImageProcessingConfiguration";
  36458. };
  36459. /**
  36460. * Prepare the list of uniforms associated with the Image Processing effects.
  36461. * @param uniformsList The list of uniforms used in the effect
  36462. * @param defines the list of defines currently in use
  36463. */
  36464. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36465. if (defines.EXPOSURE) {
  36466. uniforms.push("exposureLinear");
  36467. }
  36468. if (defines.CONTRAST) {
  36469. uniforms.push("contrast");
  36470. }
  36471. if (defines.COLORGRADING) {
  36472. uniforms.push("colorTransformSettings");
  36473. }
  36474. if (defines.VIGNETTE) {
  36475. uniforms.push("vInverseScreenSize");
  36476. uniforms.push("vignetteSettings1");
  36477. uniforms.push("vignetteSettings2");
  36478. }
  36479. if (defines.COLORCURVES) {
  36480. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36481. }
  36482. };
  36483. /**
  36484. * Prepare the list of samplers associated with the Image Processing effects.
  36485. * @param uniformsList The list of uniforms used in the effect
  36486. * @param defines the list of defines currently in use
  36487. */
  36488. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36489. if (defines.COLORGRADING) {
  36490. samplersList.push("txColorTransform");
  36491. }
  36492. };
  36493. /**
  36494. * Prepare the list of defines associated to the shader.
  36495. * @param defines the list of defines to complete
  36496. */
  36497. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36498. if (forPostProcess === void 0) { forPostProcess = false; }
  36499. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36500. defines.VIGNETTE = false;
  36501. defines.TONEMAPPING = false;
  36502. defines.CONTRAST = false;
  36503. defines.EXPOSURE = false;
  36504. defines.COLORCURVES = false;
  36505. defines.COLORGRADING = false;
  36506. defines.COLORGRADING3D = false;
  36507. defines.IMAGEPROCESSING = false;
  36508. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36509. return;
  36510. }
  36511. defines.VIGNETTE = this.vignetteEnabled;
  36512. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36513. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36514. defines.TONEMAPPING = this.toneMappingEnabled;
  36515. defines.CONTRAST = (this.contrast !== 1.0);
  36516. defines.EXPOSURE = (this.exposure !== 1.0);
  36517. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36518. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36519. if (defines.COLORGRADING) {
  36520. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36521. }
  36522. else {
  36523. defines.COLORGRADING3D = false;
  36524. }
  36525. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36526. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36527. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36528. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36529. };
  36530. /**
  36531. * Returns true if all the image processing information are ready.
  36532. */
  36533. ImageProcessingConfiguration.prototype.isReady = function () {
  36534. // Color Grading texure can not be none blocking.
  36535. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36536. };
  36537. /**
  36538. * Binds the image processing to the shader.
  36539. * @param effect The effect to bind to
  36540. */
  36541. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36542. if (aspectRatio === void 0) { aspectRatio = 1; }
  36543. // Color Curves
  36544. if (this._colorCurvesEnabled && this.colorCurves) {
  36545. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36546. }
  36547. // Vignette
  36548. if (this._vignetteEnabled) {
  36549. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36550. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36551. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36552. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36553. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36554. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36555. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36556. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36557. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36558. var vignettePower = -2.0 * this.vignetteWeight;
  36559. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36560. }
  36561. // Exposure
  36562. effect.setFloat("exposureLinear", this.exposure);
  36563. // Contrast
  36564. effect.setFloat("contrast", this.contrast);
  36565. // Color transform settings
  36566. if (this.colorGradingTexture) {
  36567. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36568. var textureSize = this.colorGradingTexture.getSize().height;
  36569. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36570. 0.5 / textureSize, // textureOffset
  36571. textureSize, // textureSize
  36572. this.colorGradingTexture.level // weight
  36573. );
  36574. }
  36575. };
  36576. /**
  36577. * Clones the current image processing instance.
  36578. * @return The cloned image processing
  36579. */
  36580. ImageProcessingConfiguration.prototype.clone = function () {
  36581. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36582. };
  36583. /**
  36584. * Serializes the current image processing instance to a json representation.
  36585. * @return a JSON representation
  36586. */
  36587. ImageProcessingConfiguration.prototype.serialize = function () {
  36588. return BABYLON.SerializationHelper.Serialize(this);
  36589. };
  36590. /**
  36591. * Parses the image processing from a json representation.
  36592. * @param source the JSON source to parse
  36593. * @return The parsed image processing
  36594. */
  36595. ImageProcessingConfiguration.Parse = function (source) {
  36596. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36597. };
  36598. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36599. /**
  36600. * Used to apply the vignette as a mix with the pixel color.
  36601. */
  36602. get: function () {
  36603. return this._VIGNETTEMODE_MULTIPLY;
  36604. },
  36605. enumerable: true,
  36606. configurable: true
  36607. });
  36608. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36609. /**
  36610. * Used to apply the vignette as a replacement of the pixel color.
  36611. */
  36612. get: function () {
  36613. return this._VIGNETTEMODE_OPAQUE;
  36614. },
  36615. enumerable: true,
  36616. configurable: true
  36617. });
  36618. // Static constants associated to the image processing.
  36619. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36620. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36621. __decorate([
  36622. BABYLON.serializeAsColorCurves()
  36623. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36624. __decorate([
  36625. BABYLON.serialize()
  36626. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36627. __decorate([
  36628. BABYLON.serializeAsTexture()
  36629. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36630. __decorate([
  36631. BABYLON.serialize()
  36632. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36633. __decorate([
  36634. BABYLON.serialize()
  36635. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36636. __decorate([
  36637. BABYLON.serialize()
  36638. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36639. __decorate([
  36640. BABYLON.serialize()
  36641. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36642. __decorate([
  36643. BABYLON.serialize()
  36644. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36645. __decorate([
  36646. BABYLON.serialize()
  36647. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36648. __decorate([
  36649. BABYLON.serialize()
  36650. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36651. __decorate([
  36652. BABYLON.serialize()
  36653. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36654. __decorate([
  36655. BABYLON.serialize()
  36656. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36657. __decorate([
  36658. BABYLON.serialize()
  36659. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36660. __decorate([
  36661. BABYLON.serializeAsColor4()
  36662. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36663. __decorate([
  36664. BABYLON.serialize()
  36665. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36666. __decorate([
  36667. BABYLON.serialize()
  36668. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36669. __decorate([
  36670. BABYLON.serialize()
  36671. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36672. __decorate([
  36673. BABYLON.serialize()
  36674. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36675. __decorate([
  36676. BABYLON.serialize()
  36677. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36678. return ImageProcessingConfiguration;
  36679. }());
  36680. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36681. })(BABYLON || (BABYLON = {}));
  36682. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36683. var BABYLON;
  36684. (function (BABYLON) {
  36685. /**
  36686. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36687. * It can help converting any input color in a desired output one. This can then be used to create effects
  36688. * from sepia, black and white to sixties or futuristic rendering...
  36689. *
  36690. * The only supported format is currently 3dl.
  36691. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36692. */
  36693. var ColorGradingTexture = /** @class */ (function (_super) {
  36694. __extends(ColorGradingTexture, _super);
  36695. /**
  36696. * Instantiates a ColorGradingTexture from the following parameters.
  36697. *
  36698. * @param url The location of the color gradind data (currently only supporting 3dl)
  36699. * @param scene The scene the texture will be used in
  36700. */
  36701. function ColorGradingTexture(url, scene) {
  36702. var _this = _super.call(this, scene) || this;
  36703. if (!url) {
  36704. return _this;
  36705. }
  36706. _this._engine = scene.getEngine();
  36707. _this._textureMatrix = BABYLON.Matrix.Identity();
  36708. _this.name = url;
  36709. _this.url = url;
  36710. _this.hasAlpha = false;
  36711. _this.isCube = false;
  36712. _this.is3D = _this._engine.webGLVersion > 1;
  36713. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36714. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36715. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36716. _this.anisotropicFilteringLevel = 1;
  36717. _this._texture = _this._getFromCache(url, true);
  36718. if (!_this._texture) {
  36719. if (!scene.useDelayedTextureLoading) {
  36720. _this.loadTexture();
  36721. }
  36722. else {
  36723. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36724. }
  36725. }
  36726. return _this;
  36727. }
  36728. /**
  36729. * Returns the texture matrix used in most of the material.
  36730. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36731. */
  36732. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36733. return this._textureMatrix;
  36734. };
  36735. /**
  36736. * Occurs when the file being loaded is a .3dl LUT file.
  36737. */
  36738. ColorGradingTexture.prototype.load3dlTexture = function () {
  36739. var engine = this._engine;
  36740. var texture;
  36741. if (engine.webGLVersion === 1) {
  36742. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36743. }
  36744. else {
  36745. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36746. }
  36747. this._texture = texture;
  36748. var callback = function (text) {
  36749. if (typeof text !== "string") {
  36750. return;
  36751. }
  36752. var data = null;
  36753. var tempData = null;
  36754. var line;
  36755. var lines = text.split('\n');
  36756. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36757. var maxColor = 0;
  36758. for (var i = 0; i < lines.length; i++) {
  36759. line = lines[i];
  36760. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36761. continue;
  36762. if (line.indexOf('#') === 0)
  36763. continue;
  36764. var words = line.split(" ");
  36765. if (size === 0) {
  36766. // Number of space + one
  36767. size = words.length;
  36768. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36769. tempData = new Float32Array(size * size * size * 4);
  36770. continue;
  36771. }
  36772. if (size != 0) {
  36773. var r = Math.max(parseInt(words[0]), 0);
  36774. var g = Math.max(parseInt(words[1]), 0);
  36775. var b = Math.max(parseInt(words[2]), 0);
  36776. maxColor = Math.max(r, maxColor);
  36777. maxColor = Math.max(g, maxColor);
  36778. maxColor = Math.max(b, maxColor);
  36779. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36780. if (tempData) {
  36781. tempData[pixelStorageIndex + 0] = r;
  36782. tempData[pixelStorageIndex + 1] = g;
  36783. tempData[pixelStorageIndex + 2] = b;
  36784. }
  36785. pixelIndexSlice++;
  36786. if (pixelIndexSlice % size == 0) {
  36787. pixelIndexH++;
  36788. pixelIndexSlice = 0;
  36789. if (pixelIndexH % size == 0) {
  36790. pixelIndexW++;
  36791. pixelIndexH = 0;
  36792. }
  36793. }
  36794. }
  36795. }
  36796. if (tempData && data) {
  36797. for (var i = 0; i < tempData.length; i++) {
  36798. if (i > 0 && (i + 1) % 4 === 0) {
  36799. data[i] = 255;
  36800. }
  36801. else {
  36802. var value = tempData[i];
  36803. data[i] = (value / maxColor * 255);
  36804. }
  36805. }
  36806. }
  36807. if (texture.is3D) {
  36808. texture.updateSize(size, size, size);
  36809. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36810. }
  36811. else {
  36812. texture.updateSize(size * size, size);
  36813. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36814. }
  36815. };
  36816. var scene = this.getScene();
  36817. if (scene) {
  36818. scene._loadFile(this.url, callback);
  36819. }
  36820. else {
  36821. this._engine._loadFile(this.url, callback);
  36822. }
  36823. return this._texture;
  36824. };
  36825. /**
  36826. * Starts the loading process of the texture.
  36827. */
  36828. ColorGradingTexture.prototype.loadTexture = function () {
  36829. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36830. this.load3dlTexture();
  36831. }
  36832. };
  36833. /**
  36834. * Clones the color gradind texture.
  36835. */
  36836. ColorGradingTexture.prototype.clone = function () {
  36837. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36838. // Base texture
  36839. newTexture.level = this.level;
  36840. return newTexture;
  36841. };
  36842. /**
  36843. * Called during delayed load for textures.
  36844. */
  36845. ColorGradingTexture.prototype.delayLoad = function () {
  36846. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36847. return;
  36848. }
  36849. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36850. this._texture = this._getFromCache(this.url, true);
  36851. if (!this._texture) {
  36852. this.loadTexture();
  36853. }
  36854. };
  36855. /**
  36856. * Parses a color grading texture serialized by Babylon.
  36857. * @param parsedTexture The texture information being parsedTexture
  36858. * @param scene The scene to load the texture in
  36859. * @param rootUrl The root url of the data assets to load
  36860. * @return A color gradind texture
  36861. */
  36862. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36863. var texture = null;
  36864. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36865. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36866. texture.name = parsedTexture.name;
  36867. texture.level = parsedTexture.level;
  36868. }
  36869. return texture;
  36870. };
  36871. /**
  36872. * Serializes the LUT texture to json format.
  36873. */
  36874. ColorGradingTexture.prototype.serialize = function () {
  36875. if (!this.name) {
  36876. return null;
  36877. }
  36878. var serializationObject = {};
  36879. serializationObject.name = this.name;
  36880. serializationObject.level = this.level;
  36881. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36882. return serializationObject;
  36883. };
  36884. /**
  36885. * Empty line regex stored for GC.
  36886. */
  36887. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36888. return ColorGradingTexture;
  36889. }(BABYLON.BaseTexture));
  36890. BABYLON.ColorGradingTexture = ColorGradingTexture;
  36891. })(BABYLON || (BABYLON = {}));
  36892. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  36893. var BABYLON;
  36894. (function (BABYLON) {
  36895. /**
  36896. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36897. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36898. * 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;
  36899. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36900. */
  36901. var ColorCurves = /** @class */ (function () {
  36902. function ColorCurves() {
  36903. this._dirty = true;
  36904. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  36905. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  36906. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36907. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  36908. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36909. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  36910. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  36911. this._globalHue = 30;
  36912. this._globalDensity = 0;
  36913. this._globalSaturation = 0;
  36914. this._globalExposure = 0;
  36915. this._highlightsHue = 30;
  36916. this._highlightsDensity = 0;
  36917. this._highlightsSaturation = 0;
  36918. this._highlightsExposure = 0;
  36919. this._midtonesHue = 30;
  36920. this._midtonesDensity = 0;
  36921. this._midtonesSaturation = 0;
  36922. this._midtonesExposure = 0;
  36923. this._shadowsHue = 30;
  36924. this._shadowsDensity = 0;
  36925. this._shadowsSaturation = 0;
  36926. this._shadowsExposure = 0;
  36927. }
  36928. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  36929. /**
  36930. * Gets the global Hue value.
  36931. * 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).
  36932. */
  36933. get: function () {
  36934. return this._globalHue;
  36935. },
  36936. /**
  36937. * Sets the global Hue value.
  36938. * 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).
  36939. */
  36940. set: function (value) {
  36941. this._globalHue = value;
  36942. this._dirty = true;
  36943. },
  36944. enumerable: true,
  36945. configurable: true
  36946. });
  36947. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  36948. /**
  36949. * Gets the global Density value.
  36950. * 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.
  36951. * Values less than zero provide a filter of opposite hue.
  36952. */
  36953. get: function () {
  36954. return this._globalDensity;
  36955. },
  36956. /**
  36957. * Sets the global Density value.
  36958. * 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.
  36959. * Values less than zero provide a filter of opposite hue.
  36960. */
  36961. set: function (value) {
  36962. this._globalDensity = value;
  36963. this._dirty = true;
  36964. },
  36965. enumerable: true,
  36966. configurable: true
  36967. });
  36968. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  36969. /**
  36970. * Gets the global Saturation value.
  36971. * 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.
  36972. */
  36973. get: function () {
  36974. return this._globalSaturation;
  36975. },
  36976. /**
  36977. * Sets the global Saturation value.
  36978. * 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.
  36979. */
  36980. set: function (value) {
  36981. this._globalSaturation = value;
  36982. this._dirty = true;
  36983. },
  36984. enumerable: true,
  36985. configurable: true
  36986. });
  36987. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  36988. /**
  36989. * Gets the highlights Hue value.
  36990. * 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).
  36991. */
  36992. get: function () {
  36993. return this._highlightsHue;
  36994. },
  36995. /**
  36996. * Sets the highlights Hue value.
  36997. * 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).
  36998. */
  36999. set: function (value) {
  37000. this._highlightsHue = value;
  37001. this._dirty = true;
  37002. },
  37003. enumerable: true,
  37004. configurable: true
  37005. });
  37006. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37007. /**
  37008. * Gets the highlights Density value.
  37009. * 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.
  37010. * Values less than zero provide a filter of opposite hue.
  37011. */
  37012. get: function () {
  37013. return this._highlightsDensity;
  37014. },
  37015. /**
  37016. * Sets the highlights Density value.
  37017. * 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.
  37018. * Values less than zero provide a filter of opposite hue.
  37019. */
  37020. set: function (value) {
  37021. this._highlightsDensity = value;
  37022. this._dirty = true;
  37023. },
  37024. enumerable: true,
  37025. configurable: true
  37026. });
  37027. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37028. /**
  37029. * Gets the highlights Saturation value.
  37030. * 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.
  37031. */
  37032. get: function () {
  37033. return this._highlightsSaturation;
  37034. },
  37035. /**
  37036. * Sets the highlights Saturation value.
  37037. * 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.
  37038. */
  37039. set: function (value) {
  37040. this._highlightsSaturation = value;
  37041. this._dirty = true;
  37042. },
  37043. enumerable: true,
  37044. configurable: true
  37045. });
  37046. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37047. /**
  37048. * Gets the highlights Exposure value.
  37049. * 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.
  37050. */
  37051. get: function () {
  37052. return this._highlightsExposure;
  37053. },
  37054. /**
  37055. * Sets the highlights Exposure value.
  37056. * 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.
  37057. */
  37058. set: function (value) {
  37059. this._highlightsExposure = value;
  37060. this._dirty = true;
  37061. },
  37062. enumerable: true,
  37063. configurable: true
  37064. });
  37065. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37066. /**
  37067. * Gets the midtones Hue value.
  37068. * 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).
  37069. */
  37070. get: function () {
  37071. return this._midtonesHue;
  37072. },
  37073. /**
  37074. * Sets the midtones Hue value.
  37075. * 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).
  37076. */
  37077. set: function (value) {
  37078. this._midtonesHue = value;
  37079. this._dirty = true;
  37080. },
  37081. enumerable: true,
  37082. configurable: true
  37083. });
  37084. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37085. /**
  37086. * Gets the midtones Density value.
  37087. * 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.
  37088. * Values less than zero provide a filter of opposite hue.
  37089. */
  37090. get: function () {
  37091. return this._midtonesDensity;
  37092. },
  37093. /**
  37094. * Sets the midtones Density value.
  37095. * 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.
  37096. * Values less than zero provide a filter of opposite hue.
  37097. */
  37098. set: function (value) {
  37099. this._midtonesDensity = value;
  37100. this._dirty = true;
  37101. },
  37102. enumerable: true,
  37103. configurable: true
  37104. });
  37105. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37106. /**
  37107. * Gets the midtones Saturation value.
  37108. * 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.
  37109. */
  37110. get: function () {
  37111. return this._midtonesSaturation;
  37112. },
  37113. /**
  37114. * Sets the midtones Saturation value.
  37115. * 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.
  37116. */
  37117. set: function (value) {
  37118. this._midtonesSaturation = value;
  37119. this._dirty = true;
  37120. },
  37121. enumerable: true,
  37122. configurable: true
  37123. });
  37124. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37125. /**
  37126. * Gets the midtones Exposure value.
  37127. * 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.
  37128. */
  37129. get: function () {
  37130. return this._midtonesExposure;
  37131. },
  37132. /**
  37133. * Sets the midtones Exposure value.
  37134. * 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.
  37135. */
  37136. set: function (value) {
  37137. this._midtonesExposure = value;
  37138. this._dirty = true;
  37139. },
  37140. enumerable: true,
  37141. configurable: true
  37142. });
  37143. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37144. /**
  37145. * Gets the shadows Hue value.
  37146. * 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).
  37147. */
  37148. get: function () {
  37149. return this._shadowsHue;
  37150. },
  37151. /**
  37152. * Sets the shadows Hue value.
  37153. * 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).
  37154. */
  37155. set: function (value) {
  37156. this._shadowsHue = value;
  37157. this._dirty = true;
  37158. },
  37159. enumerable: true,
  37160. configurable: true
  37161. });
  37162. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37163. /**
  37164. * Gets the shadows Density value.
  37165. * 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.
  37166. * Values less than zero provide a filter of opposite hue.
  37167. */
  37168. get: function () {
  37169. return this._shadowsDensity;
  37170. },
  37171. /**
  37172. * Sets the shadows Density value.
  37173. * 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.
  37174. * Values less than zero provide a filter of opposite hue.
  37175. */
  37176. set: function (value) {
  37177. this._shadowsDensity = value;
  37178. this._dirty = true;
  37179. },
  37180. enumerable: true,
  37181. configurable: true
  37182. });
  37183. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37184. /**
  37185. * Gets the shadows Saturation value.
  37186. * 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.
  37187. */
  37188. get: function () {
  37189. return this._shadowsSaturation;
  37190. },
  37191. /**
  37192. * Sets the shadows Saturation value.
  37193. * 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.
  37194. */
  37195. set: function (value) {
  37196. this._shadowsSaturation = value;
  37197. this._dirty = true;
  37198. },
  37199. enumerable: true,
  37200. configurable: true
  37201. });
  37202. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37203. /**
  37204. * Gets the shadows Exposure value.
  37205. * 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.
  37206. */
  37207. get: function () {
  37208. return this._shadowsExposure;
  37209. },
  37210. /**
  37211. * Sets the shadows Exposure value.
  37212. * 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.
  37213. */
  37214. set: function (value) {
  37215. this._shadowsExposure = value;
  37216. this._dirty = true;
  37217. },
  37218. enumerable: true,
  37219. configurable: true
  37220. });
  37221. ColorCurves.prototype.getClassName = function () {
  37222. return "ColorCurves";
  37223. };
  37224. /**
  37225. * Binds the color curves to the shader.
  37226. * @param colorCurves The color curve to bind
  37227. * @param effect The effect to bind to
  37228. */
  37229. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37230. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37231. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37232. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37233. if (colorCurves._dirty) {
  37234. colorCurves._dirty = false;
  37235. // Fill in global info.
  37236. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37237. // Compute highlights info.
  37238. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37239. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37240. // Compute midtones info.
  37241. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37242. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37243. // Compute shadows info.
  37244. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37245. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37246. // Compute deltas (neutral is midtones).
  37247. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37248. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37249. }
  37250. if (effect) {
  37251. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37252. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37253. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37254. }
  37255. };
  37256. /**
  37257. * Prepare the list of uniforms associated with the ColorCurves effects.
  37258. * @param uniformsList The list of uniforms used in the effect
  37259. */
  37260. ColorCurves.PrepareUniforms = function (uniformsList) {
  37261. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37262. };
  37263. /**
  37264. * Returns color grading data based on a hue, density, saturation and exposure value.
  37265. * @param filterHue The hue of the color filter.
  37266. * @param filterDensity The density of the color filter.
  37267. * @param saturation The saturation.
  37268. * @param exposure The exposure.
  37269. * @param result The result data container.
  37270. */
  37271. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37272. if (hue == null) {
  37273. return;
  37274. }
  37275. hue = ColorCurves.clamp(hue, 0, 360);
  37276. density = ColorCurves.clamp(density, -100, 100);
  37277. saturation = ColorCurves.clamp(saturation, -100, 100);
  37278. exposure = ColorCurves.clamp(exposure, -100, 100);
  37279. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37280. // so that the maximum filter density is only 50% control. This provides fine control
  37281. // for small values and reasonable range.
  37282. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37283. density *= 0.5;
  37284. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37285. if (density < 0) {
  37286. density *= -1;
  37287. hue = (hue + 180) % 360;
  37288. }
  37289. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37290. result.scaleToRef(2, result);
  37291. result.a = 1 + 0.01 * saturation;
  37292. };
  37293. /**
  37294. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37295. * @param value The input slider value in range [-100,100].
  37296. * @returns Adjusted value.
  37297. */
  37298. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37299. value /= 100;
  37300. var x = Math.abs(value);
  37301. x = Math.pow(x, 2);
  37302. if (value < 0) {
  37303. x *= -1;
  37304. }
  37305. x *= 100;
  37306. return x;
  37307. };
  37308. /**
  37309. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37310. * @param hue The hue (H) input.
  37311. * @param saturation The saturation (S) input.
  37312. * @param brightness The brightness (B) input.
  37313. * @result An RGBA color represented as Vector4.
  37314. */
  37315. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37316. var h = ColorCurves.clamp(hue, 0, 360);
  37317. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37318. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37319. if (s === 0) {
  37320. result.r = v;
  37321. result.g = v;
  37322. result.b = v;
  37323. }
  37324. else {
  37325. // sector 0 to 5
  37326. h /= 60;
  37327. var i = Math.floor(h);
  37328. // fractional part of h
  37329. var f = h - i;
  37330. var p = v * (1 - s);
  37331. var q = v * (1 - s * f);
  37332. var t = v * (1 - s * (1 - f));
  37333. switch (i) {
  37334. case 0:
  37335. result.r = v;
  37336. result.g = t;
  37337. result.b = p;
  37338. break;
  37339. case 1:
  37340. result.r = q;
  37341. result.g = v;
  37342. result.b = p;
  37343. break;
  37344. case 2:
  37345. result.r = p;
  37346. result.g = v;
  37347. result.b = t;
  37348. break;
  37349. case 3:
  37350. result.r = p;
  37351. result.g = q;
  37352. result.b = v;
  37353. break;
  37354. case 4:
  37355. result.r = t;
  37356. result.g = p;
  37357. result.b = v;
  37358. break;
  37359. default:// case 5:
  37360. result.r = v;
  37361. result.g = p;
  37362. result.b = q;
  37363. break;
  37364. }
  37365. }
  37366. result.a = 1;
  37367. };
  37368. /**
  37369. * Returns a value clamped between min and max
  37370. * @param value The value to clamp
  37371. * @param min The minimum of value
  37372. * @param max The maximum of value
  37373. * @returns The clamped value.
  37374. */
  37375. ColorCurves.clamp = function (value, min, max) {
  37376. return Math.min(Math.max(value, min), max);
  37377. };
  37378. /**
  37379. * Clones the current color curve instance.
  37380. * @return The cloned curves
  37381. */
  37382. ColorCurves.prototype.clone = function () {
  37383. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37384. };
  37385. /**
  37386. * Serializes the current color curve instance to a json representation.
  37387. * @return a JSON representation
  37388. */
  37389. ColorCurves.prototype.serialize = function () {
  37390. return BABYLON.SerializationHelper.Serialize(this);
  37391. };
  37392. /**
  37393. * Parses the color curve from a json representation.
  37394. * @param source the JSON source to parse
  37395. * @return The parsed curves
  37396. */
  37397. ColorCurves.Parse = function (source) {
  37398. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37399. };
  37400. __decorate([
  37401. BABYLON.serialize()
  37402. ], ColorCurves.prototype, "_globalHue", void 0);
  37403. __decorate([
  37404. BABYLON.serialize()
  37405. ], ColorCurves.prototype, "_globalDensity", void 0);
  37406. __decorate([
  37407. BABYLON.serialize()
  37408. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37409. __decorate([
  37410. BABYLON.serialize()
  37411. ], ColorCurves.prototype, "_globalExposure", void 0);
  37412. __decorate([
  37413. BABYLON.serialize()
  37414. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37415. __decorate([
  37416. BABYLON.serialize()
  37417. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37418. __decorate([
  37419. BABYLON.serialize()
  37420. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37421. __decorate([
  37422. BABYLON.serialize()
  37423. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37424. __decorate([
  37425. BABYLON.serialize()
  37426. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37427. __decorate([
  37428. BABYLON.serialize()
  37429. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37430. __decorate([
  37431. BABYLON.serialize()
  37432. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37433. __decorate([
  37434. BABYLON.serialize()
  37435. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37436. return ColorCurves;
  37437. }());
  37438. BABYLON.ColorCurves = ColorCurves;
  37439. })(BABYLON || (BABYLON = {}));
  37440. //# sourceMappingURL=babylon.colorCurves.js.map
  37441. //# sourceMappingURL=babylon.behavior.js.map
  37442. var BABYLON;
  37443. (function (BABYLON) {
  37444. /**
  37445. * "Static Class" containing the most commonly used helper while dealing with material for
  37446. * rendering purpose.
  37447. *
  37448. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37449. *
  37450. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37451. */
  37452. var MaterialHelper = /** @class */ (function () {
  37453. function MaterialHelper() {
  37454. }
  37455. /**
  37456. * Bind the current view position to an effect.
  37457. * @param effect The effect to be bound
  37458. * @param scene The scene the eyes position is used from
  37459. */
  37460. MaterialHelper.BindEyePosition = function (effect, scene) {
  37461. if (scene._forcedViewPosition) {
  37462. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37463. return;
  37464. }
  37465. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37466. };
  37467. /**
  37468. * Helps preparing the defines values about the UVs in used in the effect.
  37469. * UVs are shared as much as we can accross chanels in the shaders.
  37470. * @param texture The texture we are preparing the UVs for
  37471. * @param defines The defines to update
  37472. * @param key The chanel key "diffuse", "specular"... used in the shader
  37473. */
  37474. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37475. defines._needUVs = true;
  37476. defines[key] = true;
  37477. if (texture.getTextureMatrix().isIdentity(true)) {
  37478. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37479. if (texture.coordinatesIndex === 0) {
  37480. defines["MAINUV1"] = true;
  37481. }
  37482. else {
  37483. defines["MAINUV2"] = true;
  37484. }
  37485. }
  37486. else {
  37487. defines[key + "DIRECTUV"] = 0;
  37488. }
  37489. };
  37490. /**
  37491. * Binds a texture matrix value to its corrsponding uniform
  37492. * @param texture The texture to bind the matrix for
  37493. * @param uniformBuffer The uniform buffer receivin the data
  37494. * @param key The chanel key "diffuse", "specular"... used in the shader
  37495. */
  37496. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37497. var matrix = texture.getTextureMatrix();
  37498. if (!matrix.isIdentity(true)) {
  37499. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37500. }
  37501. };
  37502. /**
  37503. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37504. * @param mesh defines the current mesh
  37505. * @param scene defines the current scene
  37506. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37507. * @param pointsCloud defines if point cloud rendering has to be turned on
  37508. * @param fogEnabled defines if fog has to be turned on
  37509. * @param alphaTest defines if alpha testing has to be turned on
  37510. * @param defines defines the current list of defines
  37511. */
  37512. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37513. if (defines._areMiscDirty) {
  37514. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37515. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37516. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37517. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37518. defines["ALPHATEST"] = alphaTest;
  37519. }
  37520. };
  37521. /**
  37522. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37523. * @param scene defines the current scene
  37524. * @param engine defines the current engine
  37525. * @param defines specifies the list of active defines
  37526. * @param useInstances defines if instances have to be turned on
  37527. * @param useClipPlane defines if clip plane have to be turned on
  37528. */
  37529. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37530. if (useClipPlane === void 0) { useClipPlane = null; }
  37531. var changed = false;
  37532. if (useClipPlane == null) {
  37533. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37534. }
  37535. if (defines["CLIPPLANE"] !== useClipPlane) {
  37536. defines["CLIPPLANE"] = useClipPlane;
  37537. changed = true;
  37538. }
  37539. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37540. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37541. changed = true;
  37542. }
  37543. if (defines["INSTANCES"] !== useInstances) {
  37544. defines["INSTANCES"] = useInstances;
  37545. changed = true;
  37546. }
  37547. if (changed) {
  37548. defines.markAsUnprocessed();
  37549. }
  37550. };
  37551. /**
  37552. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37553. * @param mesh The mesh containing the geometry data we will draw
  37554. * @param defines The defines to update
  37555. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37556. * @param useBones Precise whether bones should be used or not (override mesh info)
  37557. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37558. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37559. * @returns false if defines are considered not dirty and have not been checked
  37560. */
  37561. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37562. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37563. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37564. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37565. return false;
  37566. }
  37567. defines._normals = defines._needNormals;
  37568. defines._uvs = defines._needUVs;
  37569. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37570. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37571. defines["TANGENT"] = true;
  37572. }
  37573. if (defines._needUVs) {
  37574. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37575. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37576. }
  37577. else {
  37578. defines["UV1"] = false;
  37579. defines["UV2"] = false;
  37580. }
  37581. if (useVertexColor) {
  37582. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37583. defines["VERTEXCOLOR"] = hasVertexColors;
  37584. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37585. }
  37586. if (useBones) {
  37587. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37588. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37589. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37590. }
  37591. else {
  37592. defines["NUM_BONE_INFLUENCERS"] = 0;
  37593. defines["BonesPerMesh"] = 0;
  37594. }
  37595. }
  37596. if (useMorphTargets) {
  37597. var manager = mesh.morphTargetManager;
  37598. if (manager) {
  37599. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37600. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37601. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37602. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37603. }
  37604. else {
  37605. defines["MORPHTARGETS_TANGENT"] = false;
  37606. defines["MORPHTARGETS_NORMAL"] = false;
  37607. defines["MORPHTARGETS"] = false;
  37608. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37609. }
  37610. }
  37611. return true;
  37612. };
  37613. /**
  37614. * Prepares the defines related to the light information passed in parameter
  37615. * @param scene The scene we are intending to draw
  37616. * @param mesh The mesh the effect is compiling for
  37617. * @param defines The defines to update
  37618. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37619. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37620. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37621. * @returns true if normals will be required for the rest of the effect
  37622. */
  37623. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37624. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37625. if (disableLighting === void 0) { disableLighting = false; }
  37626. if (!defines._areLightsDirty) {
  37627. return defines._needNormals;
  37628. }
  37629. var lightIndex = 0;
  37630. var needNormals = false;
  37631. var needRebuild = false;
  37632. var lightmapMode = false;
  37633. var shadowEnabled = false;
  37634. var specularEnabled = false;
  37635. if (scene.lightsEnabled && !disableLighting) {
  37636. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37637. var light = _a[_i];
  37638. needNormals = true;
  37639. if (defines["LIGHT" + lightIndex] === undefined) {
  37640. needRebuild = true;
  37641. }
  37642. defines["LIGHT" + lightIndex] = true;
  37643. defines["SPOTLIGHT" + lightIndex] = false;
  37644. defines["HEMILIGHT" + lightIndex] = false;
  37645. defines["POINTLIGHT" + lightIndex] = false;
  37646. defines["DIRLIGHT" + lightIndex] = false;
  37647. var type;
  37648. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37649. type = "SPOTLIGHT" + lightIndex;
  37650. var spotLight = light;
  37651. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37652. }
  37653. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37654. type = "HEMILIGHT" + lightIndex;
  37655. }
  37656. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37657. type = "POINTLIGHT" + lightIndex;
  37658. }
  37659. else {
  37660. type = "DIRLIGHT" + lightIndex;
  37661. }
  37662. defines[type] = true;
  37663. // Specular
  37664. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37665. specularEnabled = true;
  37666. }
  37667. // Shadows
  37668. defines["SHADOW" + lightIndex] = false;
  37669. defines["SHADOWPCF" + lightIndex] = false;
  37670. defines["SHADOWESM" + lightIndex] = false;
  37671. defines["SHADOWCUBE" + lightIndex] = false;
  37672. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37673. var shadowGenerator = light.getShadowGenerator();
  37674. if (shadowGenerator) {
  37675. shadowEnabled = true;
  37676. shadowGenerator.prepareDefines(defines, lightIndex);
  37677. }
  37678. }
  37679. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37680. lightmapMode = true;
  37681. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37682. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37683. }
  37684. else {
  37685. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37686. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37687. }
  37688. lightIndex++;
  37689. if (lightIndex === maxSimultaneousLights)
  37690. break;
  37691. }
  37692. }
  37693. defines["SPECULARTERM"] = specularEnabled;
  37694. defines["SHADOWS"] = shadowEnabled;
  37695. // Resetting all other lights if any
  37696. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37697. if (defines["LIGHT" + index] !== undefined) {
  37698. defines["LIGHT" + index] = false;
  37699. defines["HEMILIGHT" + lightIndex] = false;
  37700. defines["POINTLIGHT" + lightIndex] = false;
  37701. defines["DIRLIGHT" + lightIndex] = false;
  37702. defines["SPOTLIGHT" + lightIndex] = false;
  37703. defines["SHADOW" + lightIndex] = false;
  37704. }
  37705. }
  37706. var caps = scene.getEngine().getCaps();
  37707. if (defines["SHADOWFLOAT"] === undefined) {
  37708. needRebuild = true;
  37709. }
  37710. defines["SHADOWFLOAT"] = shadowEnabled &&
  37711. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37712. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37713. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37714. if (needRebuild) {
  37715. defines.rebuild();
  37716. }
  37717. return needNormals;
  37718. };
  37719. /**
  37720. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37721. * that won t be acctive due to defines being turned off.
  37722. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37723. * @param samplersList The samplers list
  37724. * @param defines The defines helping in the list generation
  37725. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37726. */
  37727. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37728. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37729. var uniformsList;
  37730. var uniformBuffersList = null;
  37731. if (uniformsListOrOptions.uniformsNames) {
  37732. var options = uniformsListOrOptions;
  37733. uniformsList = options.uniformsNames;
  37734. uniformBuffersList = options.uniformBuffersNames;
  37735. samplersList = options.samplers;
  37736. defines = options.defines;
  37737. maxSimultaneousLights = options.maxSimultaneousLights;
  37738. }
  37739. else {
  37740. uniformsList = uniformsListOrOptions;
  37741. if (!samplersList) {
  37742. samplersList = [];
  37743. }
  37744. }
  37745. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37746. if (!defines["LIGHT" + lightIndex]) {
  37747. break;
  37748. }
  37749. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37750. if (uniformBuffersList) {
  37751. uniformBuffersList.push("Light" + lightIndex);
  37752. }
  37753. samplersList.push("shadowSampler" + lightIndex);
  37754. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37755. samplersList.push("projectionLightSampler" + lightIndex);
  37756. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37757. }
  37758. }
  37759. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37760. uniformsList.push("morphTargetInfluences");
  37761. }
  37762. };
  37763. /**
  37764. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37765. * @param defines The defines to update while falling back
  37766. * @param fallbacks The authorized effect fallbacks
  37767. * @param maxSimultaneousLights The maximum number of lights allowed
  37768. * @param rank the current rank of the Effect
  37769. * @returns The newly affected rank
  37770. */
  37771. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37772. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37773. if (rank === void 0) { rank = 0; }
  37774. var lightFallbackRank = 0;
  37775. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37776. if (!defines["LIGHT" + lightIndex]) {
  37777. break;
  37778. }
  37779. if (lightIndex > 0) {
  37780. lightFallbackRank = rank + lightIndex;
  37781. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37782. }
  37783. if (!defines["SHADOWS"]) {
  37784. if (defines["SHADOW" + lightIndex]) {
  37785. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37786. }
  37787. if (defines["SHADOWPCF" + lightIndex]) {
  37788. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37789. }
  37790. if (defines["SHADOWESM" + lightIndex]) {
  37791. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37792. }
  37793. }
  37794. }
  37795. return lightFallbackRank++;
  37796. };
  37797. /**
  37798. * Prepares the list of attributes required for morph targets according to the effect defines.
  37799. * @param attribs The current list of supported attribs
  37800. * @param mesh The mesh to prepare the morph targets attributes for
  37801. * @param defines The current Defines of the effect
  37802. */
  37803. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37804. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37805. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37806. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37807. var manager = mesh.morphTargetManager;
  37808. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37809. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37810. for (var index = 0; index < influencers; index++) {
  37811. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37812. if (normal) {
  37813. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37814. }
  37815. if (tangent) {
  37816. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37817. }
  37818. if (attribs.length > maxAttributesCount) {
  37819. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37820. }
  37821. }
  37822. }
  37823. };
  37824. /**
  37825. * Prepares the list of attributes required for bones according to the effect defines.
  37826. * @param attribs The current list of supported attribs
  37827. * @param mesh The mesh to prepare the bones attributes for
  37828. * @param defines The current Defines of the effect
  37829. * @param fallbacks The current efffect fallback strategy
  37830. */
  37831. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37832. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37833. fallbacks.addCPUSkinningFallback(0, mesh);
  37834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37836. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37839. }
  37840. }
  37841. };
  37842. /**
  37843. * Prepares the list of attributes required for instances according to the effect defines.
  37844. * @param attribs The current list of supported attribs
  37845. * @param defines The current Defines of the effect
  37846. */
  37847. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37848. if (defines["INSTANCES"]) {
  37849. attribs.push("world0");
  37850. attribs.push("world1");
  37851. attribs.push("world2");
  37852. attribs.push("world3");
  37853. }
  37854. };
  37855. /**
  37856. * Binds the light shadow information to the effect for the given mesh.
  37857. * @param light The light containing the generator
  37858. * @param scene The scene the lights belongs to
  37859. * @param mesh The mesh we are binding the information to render
  37860. * @param lightIndex The light index in the effect used to render the mesh
  37861. * @param effect The effect we are binding the data to
  37862. */
  37863. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37864. if (light.shadowEnabled && mesh.receiveShadows) {
  37865. var shadowGenerator = light.getShadowGenerator();
  37866. if (shadowGenerator) {
  37867. shadowGenerator.bindShadowLight(lightIndex, effect);
  37868. }
  37869. }
  37870. };
  37871. /**
  37872. * Binds the light information to the effect.
  37873. * @param light The light containing the generator
  37874. * @param effect The effect we are binding the data to
  37875. * @param lightIndex The light index in the effect used to render
  37876. */
  37877. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37878. light.transferToEffect(effect, lightIndex + "");
  37879. };
  37880. /**
  37881. * Binds the lights information from the scene to the effect for the given mesh.
  37882. * @param scene The scene the lights belongs to
  37883. * @param mesh The mesh we are binding the information to render
  37884. * @param effect The effect we are binding the data to
  37885. * @param defines The generated defines for the effect
  37886. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37887. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37888. */
  37889. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  37890. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37891. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  37892. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  37893. for (var i = 0; i < len; i++) {
  37894. var light = mesh._lightSources[i];
  37895. var iAsString = i.toString();
  37896. var scaledIntensity = light.getScaledIntensity();
  37897. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  37898. MaterialHelper.BindLightProperties(light, effect, i);
  37899. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  37900. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  37901. if (defines["SPECULARTERM"]) {
  37902. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  37903. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  37904. }
  37905. // Shadows
  37906. if (scene.shadowsEnabled) {
  37907. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  37908. }
  37909. light._uniformBuffer.update();
  37910. }
  37911. };
  37912. /**
  37913. * Binds the fog information from the scene to the effect for the given mesh.
  37914. * @param scene The scene the lights belongs to
  37915. * @param mesh The mesh we are binding the information to render
  37916. * @param effect The effect we are binding the data to
  37917. */
  37918. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  37919. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  37920. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  37921. effect.setColor3("vFogColor", scene.fogColor);
  37922. }
  37923. };
  37924. /**
  37925. * Binds the bones information from the mesh to the effect.
  37926. * @param mesh The mesh we are binding the information to render
  37927. * @param effect The effect we are binding the data to
  37928. */
  37929. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  37930. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37931. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  37932. if (matrices && effect) {
  37933. effect.setMatrices("mBones", matrices);
  37934. }
  37935. }
  37936. };
  37937. /**
  37938. * Binds the morph targets information from the mesh to the effect.
  37939. * @param abstractMesh The mesh we are binding the information to render
  37940. * @param effect The effect we are binding the data to
  37941. */
  37942. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  37943. var manager = abstractMesh.morphTargetManager;
  37944. if (!abstractMesh || !manager) {
  37945. return;
  37946. }
  37947. effect.setFloatArray("morphTargetInfluences", manager.influences);
  37948. };
  37949. /**
  37950. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  37951. * @param defines The generated defines used in the effect
  37952. * @param effect The effect we are binding the data to
  37953. * @param scene The scene we are willing to render with logarithmic scale for
  37954. */
  37955. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  37956. if (defines["LOGARITHMICDEPTH"]) {
  37957. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  37958. }
  37959. };
  37960. /**
  37961. * Binds the clip plane information from the scene to the effect.
  37962. * @param scene The scene the clip plane information are extracted from
  37963. * @param effect The effect we are binding the data to
  37964. */
  37965. MaterialHelper.BindClipPlane = function (effect, scene) {
  37966. if (scene.clipPlane) {
  37967. var clipPlane = scene.clipPlane;
  37968. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37969. }
  37970. };
  37971. return MaterialHelper;
  37972. }());
  37973. BABYLON.MaterialHelper = MaterialHelper;
  37974. })(BABYLON || (BABYLON = {}));
  37975. //# sourceMappingURL=babylon.materialHelper.js.map
  37976. var BABYLON;
  37977. (function (BABYLON) {
  37978. var PushMaterial = /** @class */ (function (_super) {
  37979. __extends(PushMaterial, _super);
  37980. function PushMaterial(name, scene) {
  37981. var _this = _super.call(this, name, scene) || this;
  37982. _this.storeEffectOnSubMeshes = true;
  37983. return _this;
  37984. }
  37985. PushMaterial.prototype.getEffect = function () {
  37986. return this._activeEffect;
  37987. };
  37988. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  37989. if (!mesh) {
  37990. return false;
  37991. }
  37992. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  37993. return true;
  37994. }
  37995. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  37996. };
  37997. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37998. this._activeEffect.setMatrix("world", world);
  37999. };
  38000. PushMaterial.prototype.bind = function (world, mesh) {
  38001. if (!mesh) {
  38002. return;
  38003. }
  38004. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38005. };
  38006. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38007. if (effect === void 0) { effect = null; }
  38008. _super.prototype._afterBind.call(this, mesh);
  38009. this.getScene()._cachedEffect = effect;
  38010. };
  38011. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38012. if (visibility === void 0) { visibility = 1; }
  38013. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38014. };
  38015. return PushMaterial;
  38016. }(BABYLON.Material));
  38017. BABYLON.PushMaterial = PushMaterial;
  38018. })(BABYLON || (BABYLON = {}));
  38019. //# sourceMappingURL=babylon.pushMaterial.js.map
  38020. var BABYLON;
  38021. (function (BABYLON) {
  38022. /** @ignore */
  38023. var StandardMaterialDefines = /** @class */ (function (_super) {
  38024. __extends(StandardMaterialDefines, _super);
  38025. function StandardMaterialDefines() {
  38026. var _this = _super.call(this) || this;
  38027. _this.MAINUV1 = false;
  38028. _this.MAINUV2 = false;
  38029. _this.DIFFUSE = false;
  38030. _this.DIFFUSEDIRECTUV = 0;
  38031. _this.AMBIENT = false;
  38032. _this.AMBIENTDIRECTUV = 0;
  38033. _this.OPACITY = false;
  38034. _this.OPACITYDIRECTUV = 0;
  38035. _this.OPACITYRGB = false;
  38036. _this.REFLECTION = false;
  38037. _this.EMISSIVE = false;
  38038. _this.EMISSIVEDIRECTUV = 0;
  38039. _this.SPECULAR = false;
  38040. _this.SPECULARDIRECTUV = 0;
  38041. _this.BUMP = false;
  38042. _this.BUMPDIRECTUV = 0;
  38043. _this.PARALLAX = false;
  38044. _this.PARALLAXOCCLUSION = false;
  38045. _this.SPECULAROVERALPHA = false;
  38046. _this.CLIPPLANE = false;
  38047. _this.ALPHATEST = false;
  38048. _this.DEPTHPREPASS = false;
  38049. _this.ALPHAFROMDIFFUSE = false;
  38050. _this.POINTSIZE = false;
  38051. _this.FOG = false;
  38052. _this.SPECULARTERM = false;
  38053. _this.DIFFUSEFRESNEL = false;
  38054. _this.OPACITYFRESNEL = false;
  38055. _this.REFLECTIONFRESNEL = false;
  38056. _this.REFRACTIONFRESNEL = false;
  38057. _this.EMISSIVEFRESNEL = false;
  38058. _this.FRESNEL = false;
  38059. _this.NORMAL = false;
  38060. _this.UV1 = false;
  38061. _this.UV2 = false;
  38062. _this.VERTEXCOLOR = false;
  38063. _this.VERTEXALPHA = false;
  38064. _this.NUM_BONE_INFLUENCERS = 0;
  38065. _this.BonesPerMesh = 0;
  38066. _this.INSTANCES = false;
  38067. _this.GLOSSINESS = false;
  38068. _this.ROUGHNESS = false;
  38069. _this.EMISSIVEASILLUMINATION = false;
  38070. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38071. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38072. _this.LIGHTMAP = false;
  38073. _this.LIGHTMAPDIRECTUV = 0;
  38074. _this.USELIGHTMAPASSHADOWMAP = false;
  38075. _this.REFLECTIONMAP_3D = false;
  38076. _this.REFLECTIONMAP_SPHERICAL = false;
  38077. _this.REFLECTIONMAP_PLANAR = false;
  38078. _this.REFLECTIONMAP_CUBIC = false;
  38079. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38080. _this.REFLECTIONMAP_PROJECTION = false;
  38081. _this.REFLECTIONMAP_SKYBOX = false;
  38082. _this.REFLECTIONMAP_EXPLICIT = false;
  38083. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38084. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38085. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38086. _this.INVERTCUBICMAP = false;
  38087. _this.LOGARITHMICDEPTH = false;
  38088. _this.REFRACTION = false;
  38089. _this.REFRACTIONMAP_3D = false;
  38090. _this.REFLECTIONOVERALPHA = false;
  38091. _this.TWOSIDEDLIGHTING = false;
  38092. _this.SHADOWFLOAT = false;
  38093. _this.MORPHTARGETS = false;
  38094. _this.MORPHTARGETS_NORMAL = false;
  38095. _this.MORPHTARGETS_TANGENT = false;
  38096. _this.NUM_MORPH_INFLUENCERS = 0;
  38097. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38098. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38099. _this.IMAGEPROCESSING = false;
  38100. _this.VIGNETTE = false;
  38101. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38102. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38103. _this.TONEMAPPING = false;
  38104. _this.CONTRAST = false;
  38105. _this.COLORCURVES = false;
  38106. _this.COLORGRADING = false;
  38107. _this.COLORGRADING3D = false;
  38108. _this.SAMPLER3DGREENDEPTH = false;
  38109. _this.SAMPLER3DBGRMAP = false;
  38110. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38111. _this.EXPOSURE = false;
  38112. _this.rebuild();
  38113. return _this;
  38114. }
  38115. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38116. var modes = [
  38117. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38118. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38119. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38120. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38121. ];
  38122. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38123. var mode = modes_1[_i];
  38124. this[mode] = (mode === modeToEnable);
  38125. }
  38126. };
  38127. return StandardMaterialDefines;
  38128. }(BABYLON.MaterialDefines));
  38129. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38130. var StandardMaterial = /** @class */ (function (_super) {
  38131. __extends(StandardMaterial, _super);
  38132. function StandardMaterial(name, scene) {
  38133. var _this = _super.call(this, name, scene) || this;
  38134. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38135. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38136. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38137. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38138. _this.specularPower = 64;
  38139. _this._useAlphaFromDiffuseTexture = false;
  38140. _this._useEmissiveAsIllumination = false;
  38141. _this._linkEmissiveWithDiffuse = false;
  38142. _this._useSpecularOverAlpha = false;
  38143. _this._useReflectionOverAlpha = false;
  38144. _this._disableLighting = false;
  38145. _this._useParallax = false;
  38146. _this._useParallaxOcclusion = false;
  38147. _this.parallaxScaleBias = 0.05;
  38148. _this._roughness = 0;
  38149. _this.indexOfRefraction = 0.98;
  38150. _this.invertRefractionY = true;
  38151. _this._useLightmapAsShadowmap = false;
  38152. _this._useReflectionFresnelFromSpecular = false;
  38153. _this._useGlossinessFromSpecularMapAlpha = false;
  38154. _this._maxSimultaneousLights = 4;
  38155. /**
  38156. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38157. */
  38158. _this._invertNormalMapX = false;
  38159. /**
  38160. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38161. */
  38162. _this._invertNormalMapY = false;
  38163. /**
  38164. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38165. */
  38166. _this._twoSidedLighting = false;
  38167. _this._renderTargets = new BABYLON.SmartArray(16);
  38168. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38169. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38170. // Setup the default processing configuration to the scene.
  38171. _this._attachImageProcessingConfiguration(null);
  38172. _this.getRenderTargetTextures = function () {
  38173. _this._renderTargets.reset();
  38174. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38175. _this._renderTargets.push(_this._reflectionTexture);
  38176. }
  38177. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38178. _this._renderTargets.push(_this._refractionTexture);
  38179. }
  38180. return _this._renderTargets;
  38181. };
  38182. return _this;
  38183. }
  38184. ;
  38185. ;
  38186. ;
  38187. ;
  38188. ;
  38189. ;
  38190. ;
  38191. ;
  38192. ;
  38193. ;
  38194. ;
  38195. ;
  38196. ;
  38197. ;
  38198. ;
  38199. ;
  38200. ;
  38201. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38202. /**
  38203. * Gets the image processing configuration used either in this material.
  38204. */
  38205. get: function () {
  38206. return this._imageProcessingConfiguration;
  38207. },
  38208. /**
  38209. * Sets the Default image processing configuration used either in the this material.
  38210. *
  38211. * If sets to null, the scene one is in use.
  38212. */
  38213. set: function (value) {
  38214. this._attachImageProcessingConfiguration(value);
  38215. // Ensure the effect will be rebuilt.
  38216. this._markAllSubMeshesAsTexturesDirty();
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. /**
  38222. * Attaches a new image processing configuration to the Standard Material.
  38223. * @param configuration
  38224. */
  38225. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38226. var _this = this;
  38227. if (configuration === this._imageProcessingConfiguration) {
  38228. return;
  38229. }
  38230. // Detaches observer.
  38231. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38232. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38233. }
  38234. // Pick the scene configuration if needed.
  38235. if (!configuration) {
  38236. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38237. }
  38238. else {
  38239. this._imageProcessingConfiguration = configuration;
  38240. }
  38241. // Attaches observer.
  38242. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38243. _this._markAllSubMeshesAsImageProcessingDirty();
  38244. });
  38245. };
  38246. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38247. /**
  38248. * Gets wether the color curves effect is enabled.
  38249. */
  38250. get: function () {
  38251. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38252. },
  38253. /**
  38254. * Sets wether the color curves effect is enabled.
  38255. */
  38256. set: function (value) {
  38257. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38258. },
  38259. enumerable: true,
  38260. configurable: true
  38261. });
  38262. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38263. /**
  38264. * Gets wether the color grading effect is enabled.
  38265. */
  38266. get: function () {
  38267. return this.imageProcessingConfiguration.colorGradingEnabled;
  38268. },
  38269. /**
  38270. * Gets wether the color grading effect is enabled.
  38271. */
  38272. set: function (value) {
  38273. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38279. /**
  38280. * Gets wether tonemapping is enabled or not.
  38281. */
  38282. get: function () {
  38283. return this._imageProcessingConfiguration.toneMappingEnabled;
  38284. },
  38285. /**
  38286. * Sets wether tonemapping is enabled or not
  38287. */
  38288. set: function (value) {
  38289. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38290. },
  38291. enumerable: true,
  38292. configurable: true
  38293. });
  38294. ;
  38295. ;
  38296. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38297. /**
  38298. * The camera exposure used on this material.
  38299. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38300. * This corresponds to a photographic exposure.
  38301. */
  38302. get: function () {
  38303. return this._imageProcessingConfiguration.exposure;
  38304. },
  38305. /**
  38306. * The camera exposure used on this material.
  38307. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38308. * This corresponds to a photographic exposure.
  38309. */
  38310. set: function (value) {
  38311. this._imageProcessingConfiguration.exposure = value;
  38312. },
  38313. enumerable: true,
  38314. configurable: true
  38315. });
  38316. ;
  38317. ;
  38318. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38319. /**
  38320. * Gets The camera contrast used on this material.
  38321. */
  38322. get: function () {
  38323. return this._imageProcessingConfiguration.contrast;
  38324. },
  38325. /**
  38326. * Sets The camera contrast used on this material.
  38327. */
  38328. set: function (value) {
  38329. this._imageProcessingConfiguration.contrast = value;
  38330. },
  38331. enumerable: true,
  38332. configurable: true
  38333. });
  38334. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38335. /**
  38336. * Gets the Color Grading 2D Lookup Texture.
  38337. */
  38338. get: function () {
  38339. return this._imageProcessingConfiguration.colorGradingTexture;
  38340. },
  38341. /**
  38342. * Sets the Color Grading 2D Lookup Texture.
  38343. */
  38344. set: function (value) {
  38345. this._imageProcessingConfiguration.colorGradingTexture = value;
  38346. },
  38347. enumerable: true,
  38348. configurable: true
  38349. });
  38350. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38351. /**
  38352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38354. * 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;
  38355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38356. */
  38357. get: function () {
  38358. return this._imageProcessingConfiguration.colorCurves;
  38359. },
  38360. /**
  38361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38363. * 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;
  38364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38365. */
  38366. set: function (value) {
  38367. this._imageProcessingConfiguration.colorCurves = value;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. StandardMaterial.prototype.getClassName = function () {
  38373. return "StandardMaterial";
  38374. };
  38375. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38376. get: function () {
  38377. return this._useLogarithmicDepth;
  38378. },
  38379. set: function (value) {
  38380. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38381. this._markAllSubMeshesAsMiscDirty();
  38382. },
  38383. enumerable: true,
  38384. configurable: true
  38385. });
  38386. StandardMaterial.prototype.needAlphaBlending = function () {
  38387. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38388. };
  38389. StandardMaterial.prototype.needAlphaTesting = function () {
  38390. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38391. };
  38392. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38393. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38394. };
  38395. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38396. return this._diffuseTexture;
  38397. };
  38398. /**
  38399. * Child classes can use it to update shaders
  38400. */
  38401. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38402. if (useInstances === void 0) { useInstances = false; }
  38403. if (subMesh.effect && this.isFrozen) {
  38404. if (this._wasPreviouslyReady && subMesh.effect) {
  38405. return true;
  38406. }
  38407. }
  38408. if (!subMesh._materialDefines) {
  38409. subMesh._materialDefines = new StandardMaterialDefines();
  38410. }
  38411. var scene = this.getScene();
  38412. var defines = subMesh._materialDefines;
  38413. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38414. if (defines._renderId === scene.getRenderId()) {
  38415. return true;
  38416. }
  38417. }
  38418. var engine = scene.getEngine();
  38419. // Lights
  38420. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38421. // Textures
  38422. if (defines._areTexturesDirty) {
  38423. defines._needUVs = false;
  38424. defines.MAINUV1 = false;
  38425. defines.MAINUV2 = false;
  38426. if (scene.texturesEnabled) {
  38427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38428. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38429. return false;
  38430. }
  38431. else {
  38432. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38433. }
  38434. }
  38435. else {
  38436. defines.DIFFUSE = false;
  38437. }
  38438. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38439. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38440. return false;
  38441. }
  38442. else {
  38443. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38444. }
  38445. }
  38446. else {
  38447. defines.AMBIENT = false;
  38448. }
  38449. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38450. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38451. return false;
  38452. }
  38453. else {
  38454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38455. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38456. }
  38457. }
  38458. else {
  38459. defines.OPACITY = false;
  38460. }
  38461. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38462. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38463. return false;
  38464. }
  38465. else {
  38466. defines._needNormals = true;
  38467. defines.REFLECTION = true;
  38468. defines.ROUGHNESS = (this._roughness > 0);
  38469. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38470. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38471. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38472. switch (this._reflectionTexture.coordinatesMode) {
  38473. case BABYLON.Texture.CUBIC_MODE:
  38474. case BABYLON.Texture.INVCUBIC_MODE:
  38475. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38476. break;
  38477. case BABYLON.Texture.EXPLICIT_MODE:
  38478. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38479. break;
  38480. case BABYLON.Texture.PLANAR_MODE:
  38481. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38482. break;
  38483. case BABYLON.Texture.PROJECTION_MODE:
  38484. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38485. break;
  38486. case BABYLON.Texture.SKYBOX_MODE:
  38487. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38488. break;
  38489. case BABYLON.Texture.SPHERICAL_MODE:
  38490. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38491. break;
  38492. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38493. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38494. break;
  38495. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38496. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38497. break;
  38498. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38499. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38500. break;
  38501. }
  38502. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38503. }
  38504. }
  38505. else {
  38506. defines.REFLECTION = false;
  38507. }
  38508. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38509. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38510. return false;
  38511. }
  38512. else {
  38513. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38514. }
  38515. }
  38516. else {
  38517. defines.EMISSIVE = false;
  38518. }
  38519. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38520. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38521. return false;
  38522. }
  38523. else {
  38524. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38525. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38526. }
  38527. }
  38528. else {
  38529. defines.LIGHTMAP = false;
  38530. }
  38531. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38532. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38533. return false;
  38534. }
  38535. else {
  38536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38537. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38538. }
  38539. }
  38540. else {
  38541. defines.SPECULAR = false;
  38542. }
  38543. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38544. // Bump texure can not be not blocking.
  38545. if (!this._bumpTexture.isReady()) {
  38546. return false;
  38547. }
  38548. else {
  38549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38550. defines.PARALLAX = this._useParallax;
  38551. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38552. }
  38553. }
  38554. else {
  38555. defines.BUMP = false;
  38556. }
  38557. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38558. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38559. return false;
  38560. }
  38561. else {
  38562. defines._needUVs = true;
  38563. defines.REFRACTION = true;
  38564. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38565. }
  38566. }
  38567. else {
  38568. defines.REFRACTION = false;
  38569. }
  38570. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38571. }
  38572. else {
  38573. defines.DIFFUSE = false;
  38574. defines.AMBIENT = false;
  38575. defines.OPACITY = false;
  38576. defines.REFLECTION = false;
  38577. defines.EMISSIVE = false;
  38578. defines.LIGHTMAP = false;
  38579. defines.BUMP = false;
  38580. defines.REFRACTION = false;
  38581. }
  38582. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38583. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38584. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38585. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38586. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38587. }
  38588. if (defines._areImageProcessingDirty) {
  38589. if (!this._imageProcessingConfiguration.isReady()) {
  38590. return false;
  38591. }
  38592. this._imageProcessingConfiguration.prepareDefines(defines);
  38593. }
  38594. if (defines._areFresnelDirty) {
  38595. if (StandardMaterial.FresnelEnabled) {
  38596. // Fresnel
  38597. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38598. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38599. this._reflectionFresnelParameters) {
  38600. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38601. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38602. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38603. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38604. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38605. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38606. defines._needNormals = true;
  38607. defines.FRESNEL = true;
  38608. }
  38609. }
  38610. else {
  38611. defines.FRESNEL = false;
  38612. }
  38613. }
  38614. // Misc.
  38615. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38616. // Attribs
  38617. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38618. // Values that need to be evaluated on every frame
  38619. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38620. // Get correct effect
  38621. if (defines.isDirty) {
  38622. defines.markAsProcessed();
  38623. scene.resetCachedMaterial();
  38624. // Fallbacks
  38625. var fallbacks = new BABYLON.EffectFallbacks();
  38626. if (defines.REFLECTION) {
  38627. fallbacks.addFallback(0, "REFLECTION");
  38628. }
  38629. if (defines.SPECULAR) {
  38630. fallbacks.addFallback(0, "SPECULAR");
  38631. }
  38632. if (defines.BUMP) {
  38633. fallbacks.addFallback(0, "BUMP");
  38634. }
  38635. if (defines.PARALLAX) {
  38636. fallbacks.addFallback(1, "PARALLAX");
  38637. }
  38638. if (defines.PARALLAXOCCLUSION) {
  38639. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38640. }
  38641. if (defines.SPECULAROVERALPHA) {
  38642. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38643. }
  38644. if (defines.FOG) {
  38645. fallbacks.addFallback(1, "FOG");
  38646. }
  38647. if (defines.POINTSIZE) {
  38648. fallbacks.addFallback(0, "POINTSIZE");
  38649. }
  38650. if (defines.LOGARITHMICDEPTH) {
  38651. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38652. }
  38653. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38654. if (defines.SPECULARTERM) {
  38655. fallbacks.addFallback(0, "SPECULARTERM");
  38656. }
  38657. if (defines.DIFFUSEFRESNEL) {
  38658. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38659. }
  38660. if (defines.OPACITYFRESNEL) {
  38661. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38662. }
  38663. if (defines.REFLECTIONFRESNEL) {
  38664. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38665. }
  38666. if (defines.EMISSIVEFRESNEL) {
  38667. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38668. }
  38669. if (defines.FRESNEL) {
  38670. fallbacks.addFallback(4, "FRESNEL");
  38671. }
  38672. //Attributes
  38673. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38674. if (defines.NORMAL) {
  38675. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38676. }
  38677. if (defines.UV1) {
  38678. attribs.push(BABYLON.VertexBuffer.UVKind);
  38679. }
  38680. if (defines.UV2) {
  38681. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38682. }
  38683. if (defines.VERTEXCOLOR) {
  38684. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38685. }
  38686. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38687. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38688. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38689. var shaderName = "default";
  38690. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38691. "vFogInfos", "vFogColor", "pointSize",
  38692. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38693. "mBones",
  38694. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38695. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38696. "vReflectionPosition", "vReflectionSize",
  38697. "logarithmicDepthConstant", "vTangentSpaceParams"
  38698. ];
  38699. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38700. var uniformBuffers = ["Material", "Scene"];
  38701. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38702. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38703. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38704. uniformsNames: uniforms,
  38705. uniformBuffersNames: uniformBuffers,
  38706. samplers: samplers,
  38707. defines: defines,
  38708. maxSimultaneousLights: this._maxSimultaneousLights
  38709. });
  38710. if (this.customShaderNameResolve) {
  38711. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38712. }
  38713. var join = defines.toString();
  38714. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38715. attributes: attribs,
  38716. uniformsNames: uniforms,
  38717. uniformBuffersNames: uniformBuffers,
  38718. samplers: samplers,
  38719. defines: join,
  38720. fallbacks: fallbacks,
  38721. onCompiled: this.onCompiled,
  38722. onError: this.onError,
  38723. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38724. }, engine), defines);
  38725. this.buildUniformLayout();
  38726. }
  38727. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38728. return false;
  38729. }
  38730. defines._renderId = scene.getRenderId();
  38731. this._wasPreviouslyReady = true;
  38732. return true;
  38733. };
  38734. StandardMaterial.prototype.buildUniformLayout = function () {
  38735. // Order is important !
  38736. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38737. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38738. this._uniformBuffer.addUniform("opacityParts", 4);
  38739. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38740. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38741. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38742. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38743. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38744. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38745. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38746. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38747. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38748. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38749. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38750. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38751. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38752. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38753. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38754. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38755. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38756. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38757. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38758. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38759. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38760. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38761. this._uniformBuffer.addUniform("specularMatrix", 16);
  38762. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38763. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38764. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38765. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38766. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38767. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38768. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38769. this._uniformBuffer.addUniform("pointSize", 1);
  38770. this._uniformBuffer.create();
  38771. };
  38772. StandardMaterial.prototype.unbind = function () {
  38773. if (this._activeEffect) {
  38774. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38775. this._activeEffect.setTexture("reflection2DSampler", null);
  38776. }
  38777. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38778. this._activeEffect.setTexture("refraction2DSampler", null);
  38779. }
  38780. }
  38781. _super.prototype.unbind.call(this);
  38782. };
  38783. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38784. var scene = this.getScene();
  38785. var defines = subMesh._materialDefines;
  38786. if (!defines) {
  38787. return;
  38788. }
  38789. var effect = subMesh.effect;
  38790. if (!effect) {
  38791. return;
  38792. }
  38793. this._activeEffect = effect;
  38794. // Matrices
  38795. this.bindOnlyWorldMatrix(world);
  38796. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38797. // Bones
  38798. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38799. if (mustRebind) {
  38800. this._uniformBuffer.bindToEffect(effect, "Material");
  38801. this.bindViewProjection(effect);
  38802. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38803. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38804. // Fresnel
  38805. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38806. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38807. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38808. }
  38809. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38810. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38811. }
  38812. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38813. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38814. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38815. }
  38816. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38817. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38818. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38819. }
  38820. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38821. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38822. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38823. }
  38824. }
  38825. // Textures
  38826. if (scene.texturesEnabled) {
  38827. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38828. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38829. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38830. }
  38831. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38832. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38833. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38834. }
  38835. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38836. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38837. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38838. }
  38839. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38840. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38841. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38842. if (this._reflectionTexture.boundingBoxSize) {
  38843. var cubeTexture = this._reflectionTexture;
  38844. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38845. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38846. }
  38847. }
  38848. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38849. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38850. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38851. }
  38852. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38853. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38854. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38855. }
  38856. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38857. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38858. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38859. }
  38860. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38861. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38862. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38863. if (scene._mirroredCameraPosition) {
  38864. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38865. }
  38866. else {
  38867. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38868. }
  38869. }
  38870. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38871. var depth = 1.0;
  38872. if (!this._refractionTexture.isCube) {
  38873. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38874. if (this._refractionTexture.depth) {
  38875. depth = this._refractionTexture.depth;
  38876. }
  38877. }
  38878. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38879. }
  38880. }
  38881. // Point size
  38882. if (this.pointsCloud) {
  38883. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38884. }
  38885. if (defines.SPECULARTERM) {
  38886. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38887. }
  38888. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38889. // Diffuse
  38890. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  38891. }
  38892. // Textures
  38893. if (scene.texturesEnabled) {
  38894. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38895. effect.setTexture("diffuseSampler", this._diffuseTexture);
  38896. }
  38897. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38898. effect.setTexture("ambientSampler", this._ambientTexture);
  38899. }
  38900. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38901. effect.setTexture("opacitySampler", this._opacityTexture);
  38902. }
  38903. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38904. if (this._reflectionTexture.isCube) {
  38905. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  38906. }
  38907. else {
  38908. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  38909. }
  38910. }
  38911. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38912. effect.setTexture("emissiveSampler", this._emissiveTexture);
  38913. }
  38914. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38915. effect.setTexture("lightmapSampler", this._lightmapTexture);
  38916. }
  38917. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38918. effect.setTexture("specularSampler", this._specularTexture);
  38919. }
  38920. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38921. effect.setTexture("bumpSampler", this._bumpTexture);
  38922. }
  38923. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38924. var depth = 1.0;
  38925. if (this._refractionTexture.isCube) {
  38926. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  38927. }
  38928. else {
  38929. effect.setTexture("refraction2DSampler", this._refractionTexture);
  38930. }
  38931. }
  38932. }
  38933. // Clip plane
  38934. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  38935. // Colors
  38936. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  38937. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  38938. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38939. }
  38940. if (mustRebind || !this.isFrozen) {
  38941. // Lights
  38942. if (scene.lightsEnabled && !this._disableLighting) {
  38943. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  38944. }
  38945. // View
  38946. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  38947. this.bindView(effect);
  38948. }
  38949. // Fog
  38950. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  38951. // Morph targets
  38952. if (defines.NUM_MORPH_INFLUENCERS) {
  38953. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  38954. }
  38955. // Log. depth
  38956. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  38957. // image processing
  38958. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  38959. this._imageProcessingConfiguration.bind(this._activeEffect);
  38960. }
  38961. }
  38962. this._uniformBuffer.update();
  38963. this._afterBind(mesh, this._activeEffect);
  38964. };
  38965. StandardMaterial.prototype.getAnimatables = function () {
  38966. var results = [];
  38967. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  38968. results.push(this._diffuseTexture);
  38969. }
  38970. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38971. results.push(this._ambientTexture);
  38972. }
  38973. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38974. results.push(this._opacityTexture);
  38975. }
  38976. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38977. results.push(this._reflectionTexture);
  38978. }
  38979. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38980. results.push(this._emissiveTexture);
  38981. }
  38982. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  38983. results.push(this._specularTexture);
  38984. }
  38985. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38986. results.push(this._bumpTexture);
  38987. }
  38988. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38989. results.push(this._lightmapTexture);
  38990. }
  38991. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38992. results.push(this._refractionTexture);
  38993. }
  38994. return results;
  38995. };
  38996. StandardMaterial.prototype.getActiveTextures = function () {
  38997. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38998. if (this._diffuseTexture) {
  38999. activeTextures.push(this._diffuseTexture);
  39000. }
  39001. if (this._ambientTexture) {
  39002. activeTextures.push(this._ambientTexture);
  39003. }
  39004. if (this._opacityTexture) {
  39005. activeTextures.push(this._opacityTexture);
  39006. }
  39007. if (this._reflectionTexture) {
  39008. activeTextures.push(this._reflectionTexture);
  39009. }
  39010. if (this._emissiveTexture) {
  39011. activeTextures.push(this._emissiveTexture);
  39012. }
  39013. if (this._specularTexture) {
  39014. activeTextures.push(this._specularTexture);
  39015. }
  39016. if (this._bumpTexture) {
  39017. activeTextures.push(this._bumpTexture);
  39018. }
  39019. if (this._lightmapTexture) {
  39020. activeTextures.push(this._lightmapTexture);
  39021. }
  39022. if (this._refractionTexture) {
  39023. activeTextures.push(this._refractionTexture);
  39024. }
  39025. return activeTextures;
  39026. };
  39027. StandardMaterial.prototype.hasTexture = function (texture) {
  39028. if (_super.prototype.hasTexture.call(this, texture)) {
  39029. return true;
  39030. }
  39031. if (this._diffuseTexture === texture) {
  39032. return true;
  39033. }
  39034. if (this._ambientTexture === texture) {
  39035. return true;
  39036. }
  39037. if (this._opacityTexture === texture) {
  39038. return true;
  39039. }
  39040. if (this._reflectionTexture === texture) {
  39041. return true;
  39042. }
  39043. if (this._emissiveTexture === texture) {
  39044. return true;
  39045. }
  39046. if (this._specularTexture === texture) {
  39047. return true;
  39048. }
  39049. if (this._bumpTexture === texture) {
  39050. return true;
  39051. }
  39052. if (this._lightmapTexture === texture) {
  39053. return true;
  39054. }
  39055. if (this._refractionTexture === texture) {
  39056. return true;
  39057. }
  39058. return false;
  39059. };
  39060. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39061. if (forceDisposeTextures) {
  39062. if (this._diffuseTexture) {
  39063. this._diffuseTexture.dispose();
  39064. }
  39065. if (this._ambientTexture) {
  39066. this._ambientTexture.dispose();
  39067. }
  39068. if (this._opacityTexture) {
  39069. this._opacityTexture.dispose();
  39070. }
  39071. if (this._reflectionTexture) {
  39072. this._reflectionTexture.dispose();
  39073. }
  39074. if (this._emissiveTexture) {
  39075. this._emissiveTexture.dispose();
  39076. }
  39077. if (this._specularTexture) {
  39078. this._specularTexture.dispose();
  39079. }
  39080. if (this._bumpTexture) {
  39081. this._bumpTexture.dispose();
  39082. }
  39083. if (this._lightmapTexture) {
  39084. this._lightmapTexture.dispose();
  39085. }
  39086. if (this._refractionTexture) {
  39087. this._refractionTexture.dispose();
  39088. }
  39089. }
  39090. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39091. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39092. }
  39093. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39094. };
  39095. StandardMaterial.prototype.clone = function (name) {
  39096. var _this = this;
  39097. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39098. result.name = name;
  39099. result.id = name;
  39100. return result;
  39101. };
  39102. StandardMaterial.prototype.serialize = function () {
  39103. return BABYLON.SerializationHelper.Serialize(this);
  39104. };
  39105. // Statics
  39106. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39107. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39108. };
  39109. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39110. get: function () {
  39111. return StandardMaterial._DiffuseTextureEnabled;
  39112. },
  39113. set: function (value) {
  39114. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39115. return;
  39116. }
  39117. StandardMaterial._DiffuseTextureEnabled = value;
  39118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39119. },
  39120. enumerable: true,
  39121. configurable: true
  39122. });
  39123. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39124. get: function () {
  39125. return StandardMaterial._AmbientTextureEnabled;
  39126. },
  39127. set: function (value) {
  39128. if (StandardMaterial._AmbientTextureEnabled === value) {
  39129. return;
  39130. }
  39131. StandardMaterial._AmbientTextureEnabled = value;
  39132. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39138. get: function () {
  39139. return StandardMaterial._OpacityTextureEnabled;
  39140. },
  39141. set: function (value) {
  39142. if (StandardMaterial._OpacityTextureEnabled === value) {
  39143. return;
  39144. }
  39145. StandardMaterial._OpacityTextureEnabled = value;
  39146. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39147. },
  39148. enumerable: true,
  39149. configurable: true
  39150. });
  39151. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39152. get: function () {
  39153. return StandardMaterial._ReflectionTextureEnabled;
  39154. },
  39155. set: function (value) {
  39156. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39157. return;
  39158. }
  39159. StandardMaterial._ReflectionTextureEnabled = value;
  39160. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39161. },
  39162. enumerable: true,
  39163. configurable: true
  39164. });
  39165. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39166. get: function () {
  39167. return StandardMaterial._EmissiveTextureEnabled;
  39168. },
  39169. set: function (value) {
  39170. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39171. return;
  39172. }
  39173. StandardMaterial._EmissiveTextureEnabled = value;
  39174. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39180. get: function () {
  39181. return StandardMaterial._SpecularTextureEnabled;
  39182. },
  39183. set: function (value) {
  39184. if (StandardMaterial._SpecularTextureEnabled === value) {
  39185. return;
  39186. }
  39187. StandardMaterial._SpecularTextureEnabled = value;
  39188. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39189. },
  39190. enumerable: true,
  39191. configurable: true
  39192. });
  39193. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39194. get: function () {
  39195. return StandardMaterial._BumpTextureEnabled;
  39196. },
  39197. set: function (value) {
  39198. if (StandardMaterial._BumpTextureEnabled === value) {
  39199. return;
  39200. }
  39201. StandardMaterial._BumpTextureEnabled = value;
  39202. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39203. },
  39204. enumerable: true,
  39205. configurable: true
  39206. });
  39207. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39208. get: function () {
  39209. return StandardMaterial._LightmapTextureEnabled;
  39210. },
  39211. set: function (value) {
  39212. if (StandardMaterial._LightmapTextureEnabled === value) {
  39213. return;
  39214. }
  39215. StandardMaterial._LightmapTextureEnabled = value;
  39216. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39217. },
  39218. enumerable: true,
  39219. configurable: true
  39220. });
  39221. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39222. get: function () {
  39223. return StandardMaterial._RefractionTextureEnabled;
  39224. },
  39225. set: function (value) {
  39226. if (StandardMaterial._RefractionTextureEnabled === value) {
  39227. return;
  39228. }
  39229. StandardMaterial._RefractionTextureEnabled = value;
  39230. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39231. },
  39232. enumerable: true,
  39233. configurable: true
  39234. });
  39235. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39236. get: function () {
  39237. return StandardMaterial._ColorGradingTextureEnabled;
  39238. },
  39239. set: function (value) {
  39240. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39241. return;
  39242. }
  39243. StandardMaterial._ColorGradingTextureEnabled = value;
  39244. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39245. },
  39246. enumerable: true,
  39247. configurable: true
  39248. });
  39249. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39250. get: function () {
  39251. return StandardMaterial._FresnelEnabled;
  39252. },
  39253. set: function (value) {
  39254. if (StandardMaterial._FresnelEnabled === value) {
  39255. return;
  39256. }
  39257. StandardMaterial._FresnelEnabled = value;
  39258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39259. },
  39260. enumerable: true,
  39261. configurable: true
  39262. });
  39263. // Flags used to enable or disable a type of texture for all Standard Materials
  39264. StandardMaterial._DiffuseTextureEnabled = true;
  39265. StandardMaterial._AmbientTextureEnabled = true;
  39266. StandardMaterial._OpacityTextureEnabled = true;
  39267. StandardMaterial._ReflectionTextureEnabled = true;
  39268. StandardMaterial._EmissiveTextureEnabled = true;
  39269. StandardMaterial._SpecularTextureEnabled = true;
  39270. StandardMaterial._BumpTextureEnabled = true;
  39271. StandardMaterial._LightmapTextureEnabled = true;
  39272. StandardMaterial._RefractionTextureEnabled = true;
  39273. StandardMaterial._ColorGradingTextureEnabled = true;
  39274. StandardMaterial._FresnelEnabled = true;
  39275. __decorate([
  39276. BABYLON.serializeAsTexture("diffuseTexture")
  39277. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39278. __decorate([
  39279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39280. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39281. __decorate([
  39282. BABYLON.serializeAsTexture("ambientTexture")
  39283. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39284. __decorate([
  39285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39286. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39287. __decorate([
  39288. BABYLON.serializeAsTexture("opacityTexture")
  39289. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39290. __decorate([
  39291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39292. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39293. __decorate([
  39294. BABYLON.serializeAsTexture("reflectionTexture")
  39295. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39296. __decorate([
  39297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39298. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39299. __decorate([
  39300. BABYLON.serializeAsTexture("emissiveTexture")
  39301. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39302. __decorate([
  39303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39304. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39305. __decorate([
  39306. BABYLON.serializeAsTexture("specularTexture")
  39307. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39308. __decorate([
  39309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39310. ], StandardMaterial.prototype, "specularTexture", void 0);
  39311. __decorate([
  39312. BABYLON.serializeAsTexture("bumpTexture")
  39313. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39314. __decorate([
  39315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39316. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39317. __decorate([
  39318. BABYLON.serializeAsTexture("lightmapTexture")
  39319. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39320. __decorate([
  39321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39322. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39323. __decorate([
  39324. BABYLON.serializeAsTexture("refractionTexture")
  39325. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39326. __decorate([
  39327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39328. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39329. __decorate([
  39330. BABYLON.serializeAsColor3("ambient")
  39331. ], StandardMaterial.prototype, "ambientColor", void 0);
  39332. __decorate([
  39333. BABYLON.serializeAsColor3("diffuse")
  39334. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39335. __decorate([
  39336. BABYLON.serializeAsColor3("specular")
  39337. ], StandardMaterial.prototype, "specularColor", void 0);
  39338. __decorate([
  39339. BABYLON.serializeAsColor3("emissive")
  39340. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39341. __decorate([
  39342. BABYLON.serialize()
  39343. ], StandardMaterial.prototype, "specularPower", void 0);
  39344. __decorate([
  39345. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39346. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39347. __decorate([
  39348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39349. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39350. __decorate([
  39351. BABYLON.serialize("useEmissiveAsIllumination")
  39352. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39353. __decorate([
  39354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39355. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39356. __decorate([
  39357. BABYLON.serialize("linkEmissiveWithDiffuse")
  39358. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39359. __decorate([
  39360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39361. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39362. __decorate([
  39363. BABYLON.serialize("useSpecularOverAlpha")
  39364. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39365. __decorate([
  39366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39367. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39368. __decorate([
  39369. BABYLON.serialize("useReflectionOverAlpha")
  39370. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39371. __decorate([
  39372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39373. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39374. __decorate([
  39375. BABYLON.serialize("disableLighting")
  39376. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39377. __decorate([
  39378. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39379. ], StandardMaterial.prototype, "disableLighting", void 0);
  39380. __decorate([
  39381. BABYLON.serialize("useParallax")
  39382. ], StandardMaterial.prototype, "_useParallax", void 0);
  39383. __decorate([
  39384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39385. ], StandardMaterial.prototype, "useParallax", void 0);
  39386. __decorate([
  39387. BABYLON.serialize("useParallaxOcclusion")
  39388. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39389. __decorate([
  39390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39391. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39392. __decorate([
  39393. BABYLON.serialize()
  39394. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39395. __decorate([
  39396. BABYLON.serialize("roughness")
  39397. ], StandardMaterial.prototype, "_roughness", void 0);
  39398. __decorate([
  39399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39400. ], StandardMaterial.prototype, "roughness", void 0);
  39401. __decorate([
  39402. BABYLON.serialize()
  39403. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39404. __decorate([
  39405. BABYLON.serialize()
  39406. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39407. __decorate([
  39408. BABYLON.serialize("useLightmapAsShadowmap")
  39409. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39410. __decorate([
  39411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39412. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39413. __decorate([
  39414. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39415. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39416. __decorate([
  39417. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39418. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39419. __decorate([
  39420. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39421. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39422. __decorate([
  39423. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39424. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39425. __decorate([
  39426. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39427. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39428. __decorate([
  39429. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39430. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39431. __decorate([
  39432. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39433. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39434. __decorate([
  39435. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39436. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39437. __decorate([
  39438. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39439. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39440. __decorate([
  39441. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39442. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39443. __decorate([
  39444. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39445. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39446. __decorate([
  39447. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39448. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39449. __decorate([
  39450. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39451. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39452. __decorate([
  39453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39454. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39455. __decorate([
  39456. BABYLON.serialize("maxSimultaneousLights")
  39457. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39458. __decorate([
  39459. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39460. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39461. __decorate([
  39462. BABYLON.serialize("invertNormalMapX")
  39463. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39464. __decorate([
  39465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39466. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39467. __decorate([
  39468. BABYLON.serialize("invertNormalMapY")
  39469. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39470. __decorate([
  39471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39472. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39473. __decorate([
  39474. BABYLON.serialize("twoSidedLighting")
  39475. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39476. __decorate([
  39477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39478. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39479. __decorate([
  39480. BABYLON.serialize()
  39481. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39482. return StandardMaterial;
  39483. }(BABYLON.PushMaterial));
  39484. BABYLON.StandardMaterial = StandardMaterial;
  39485. })(BABYLON || (BABYLON = {}));
  39486. //# sourceMappingURL=babylon.standardMaterial.js.map
  39487. var BABYLON;
  39488. (function (BABYLON) {
  39489. /**
  39490. * Manages the defines for the PBR Material.
  39491. */
  39492. var PBRMaterialDefines = /** @class */ (function (_super) {
  39493. __extends(PBRMaterialDefines, _super);
  39494. /**
  39495. * Initializes the PBR Material defines.
  39496. */
  39497. function PBRMaterialDefines() {
  39498. var _this = _super.call(this) || this;
  39499. _this.PBR = true;
  39500. _this.MAINUV1 = false;
  39501. _this.MAINUV2 = false;
  39502. _this.UV1 = false;
  39503. _this.UV2 = false;
  39504. _this.ALBEDO = false;
  39505. _this.ALBEDODIRECTUV = 0;
  39506. _this.VERTEXCOLOR = false;
  39507. _this.AMBIENT = false;
  39508. _this.AMBIENTDIRECTUV = 0;
  39509. _this.AMBIENTINGRAYSCALE = false;
  39510. _this.OPACITY = false;
  39511. _this.VERTEXALPHA = false;
  39512. _this.OPACITYDIRECTUV = 0;
  39513. _this.OPACITYRGB = false;
  39514. _this.ALPHATEST = false;
  39515. _this.DEPTHPREPASS = false;
  39516. _this.ALPHABLEND = false;
  39517. _this.ALPHAFROMALBEDO = false;
  39518. _this.ALPHATESTVALUE = 0.5;
  39519. _this.SPECULAROVERALPHA = false;
  39520. _this.RADIANCEOVERALPHA = false;
  39521. _this.ALPHAFRESNEL = false;
  39522. _this.LINEARALPHAFRESNEL = false;
  39523. _this.PREMULTIPLYALPHA = false;
  39524. _this.EMISSIVE = false;
  39525. _this.EMISSIVEDIRECTUV = 0;
  39526. _this.REFLECTIVITY = false;
  39527. _this.REFLECTIVITYDIRECTUV = 0;
  39528. _this.SPECULARTERM = false;
  39529. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39530. _this.MICROSURFACEAUTOMATIC = false;
  39531. _this.LODBASEDMICROSFURACE = false;
  39532. _this.MICROSURFACEMAP = false;
  39533. _this.MICROSURFACEMAPDIRECTUV = 0;
  39534. _this.METALLICWORKFLOW = false;
  39535. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39536. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39537. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39538. _this.AOSTOREINMETALMAPRED = false;
  39539. _this.ENVIRONMENTBRDF = false;
  39540. _this.NORMAL = false;
  39541. _this.TANGENT = false;
  39542. _this.BUMP = false;
  39543. _this.BUMPDIRECTUV = 0;
  39544. _this.PARALLAX = false;
  39545. _this.PARALLAXOCCLUSION = false;
  39546. _this.NORMALXYSCALE = true;
  39547. _this.LIGHTMAP = false;
  39548. _this.LIGHTMAPDIRECTUV = 0;
  39549. _this.USELIGHTMAPASSHADOWMAP = false;
  39550. _this.REFLECTION = false;
  39551. _this.REFLECTIONMAP_3D = false;
  39552. _this.REFLECTIONMAP_SPHERICAL = false;
  39553. _this.REFLECTIONMAP_PLANAR = false;
  39554. _this.REFLECTIONMAP_CUBIC = false;
  39555. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39556. _this.REFLECTIONMAP_PROJECTION = false;
  39557. _this.REFLECTIONMAP_SKYBOX = false;
  39558. _this.REFLECTIONMAP_EXPLICIT = false;
  39559. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39560. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39561. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39562. _this.INVERTCUBICMAP = false;
  39563. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39564. _this.USESPHERICALINVERTEX = false;
  39565. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39566. _this.LODINREFLECTIONALPHA = false;
  39567. _this.GAMMAREFLECTION = false;
  39568. _this.RADIANCEOCCLUSION = false;
  39569. _this.HORIZONOCCLUSION = false;
  39570. _this.REFRACTION = false;
  39571. _this.REFRACTIONMAP_3D = false;
  39572. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39573. _this.LODINREFRACTIONALPHA = false;
  39574. _this.GAMMAREFRACTION = false;
  39575. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39576. _this.INSTANCES = false;
  39577. _this.NUM_BONE_INFLUENCERS = 0;
  39578. _this.BonesPerMesh = 0;
  39579. _this.NONUNIFORMSCALING = false;
  39580. _this.MORPHTARGETS = false;
  39581. _this.MORPHTARGETS_NORMAL = false;
  39582. _this.MORPHTARGETS_TANGENT = false;
  39583. _this.NUM_MORPH_INFLUENCERS = 0;
  39584. _this.IMAGEPROCESSING = false;
  39585. _this.VIGNETTE = false;
  39586. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39587. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39588. _this.TONEMAPPING = false;
  39589. _this.CONTRAST = false;
  39590. _this.COLORCURVES = false;
  39591. _this.COLORGRADING = false;
  39592. _this.COLORGRADING3D = false;
  39593. _this.SAMPLER3DGREENDEPTH = false;
  39594. _this.SAMPLER3DBGRMAP = false;
  39595. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39596. _this.EXPOSURE = false;
  39597. _this.USEPHYSICALLIGHTFALLOFF = false;
  39598. _this.TWOSIDEDLIGHTING = false;
  39599. _this.SHADOWFLOAT = false;
  39600. _this.CLIPPLANE = false;
  39601. _this.POINTSIZE = false;
  39602. _this.FOG = false;
  39603. _this.LOGARITHMICDEPTH = false;
  39604. _this.FORCENORMALFORWARD = false;
  39605. _this.rebuild();
  39606. return _this;
  39607. }
  39608. /**
  39609. * Resets the PBR Material defines.
  39610. */
  39611. PBRMaterialDefines.prototype.reset = function () {
  39612. _super.prototype.reset.call(this);
  39613. this.ALPHATESTVALUE = 0.5;
  39614. this.PBR = true;
  39615. };
  39616. return PBRMaterialDefines;
  39617. }(BABYLON.MaterialDefines));
  39618. /**
  39619. * The Physically based material base class of BJS.
  39620. *
  39621. * This offers the main features of a standard PBR material.
  39622. * For more information, please refer to the documentation :
  39623. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39624. */
  39625. var PBRBaseMaterial = /** @class */ (function (_super) {
  39626. __extends(PBRBaseMaterial, _super);
  39627. /**
  39628. * Instantiates a new PBRMaterial instance.
  39629. *
  39630. * @param name The material name
  39631. * @param scene The scene the material will be use in.
  39632. */
  39633. function PBRBaseMaterial(name, scene) {
  39634. var _this = _super.call(this, name, scene) || this;
  39635. /**
  39636. * Intensity of the direct lights e.g. the four lights available in your scene.
  39637. * This impacts both the direct diffuse and specular highlights.
  39638. */
  39639. _this._directIntensity = 1.0;
  39640. /**
  39641. * Intensity of the emissive part of the material.
  39642. * This helps controlling the emissive effect without modifying the emissive color.
  39643. */
  39644. _this._emissiveIntensity = 1.0;
  39645. /**
  39646. * Intensity of the environment e.g. how much the environment will light the object
  39647. * either through harmonics for rough material or through the refelction for shiny ones.
  39648. */
  39649. _this._environmentIntensity = 1.0;
  39650. /**
  39651. * This is a special control allowing the reduction of the specular highlights coming from the
  39652. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39653. */
  39654. _this._specularIntensity = 1.0;
  39655. /**
  39656. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39657. */
  39658. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39659. /**
  39660. * Debug Control allowing disabling the bump map on this material.
  39661. */
  39662. _this._disableBumpMap = false;
  39663. /**
  39664. * AKA Occlusion Texture Intensity in other nomenclature.
  39665. */
  39666. _this._ambientTextureStrength = 1.0;
  39667. /**
  39668. * The color of a material in ambient lighting.
  39669. */
  39670. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39671. /**
  39672. * AKA Diffuse Color in other nomenclature.
  39673. */
  39674. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39675. /**
  39676. * AKA Specular Color in other nomenclature.
  39677. */
  39678. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39679. /**
  39680. * The color applied when light is reflected from a material.
  39681. */
  39682. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39683. /**
  39684. * The color applied when light is emitted from a material.
  39685. */
  39686. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39687. /**
  39688. * AKA Glossiness in other nomenclature.
  39689. */
  39690. _this._microSurface = 0.9;
  39691. /**
  39692. * source material index of refraction (IOR)' / 'destination material IOR.
  39693. */
  39694. _this._indexOfRefraction = 0.66;
  39695. /**
  39696. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39697. */
  39698. _this._invertRefractionY = false;
  39699. /**
  39700. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39701. * Materials half opaque for instance using refraction could benefit from this control.
  39702. */
  39703. _this._linkRefractionWithTransparency = false;
  39704. /**
  39705. * Specifies that the material will use the light map as a show map.
  39706. */
  39707. _this._useLightmapAsShadowmap = false;
  39708. /**
  39709. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39710. * makes the reflect vector face the model (under horizon).
  39711. */
  39712. _this._useHorizonOcclusion = true;
  39713. /**
  39714. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39715. * too much the area relying on ambient texture to define their ambient occlusion.
  39716. */
  39717. _this._useRadianceOcclusion = true;
  39718. /**
  39719. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39720. */
  39721. _this._useAlphaFromAlbedoTexture = false;
  39722. /**
  39723. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39724. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39725. */
  39726. _this._useSpecularOverAlpha = true;
  39727. /**
  39728. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39729. */
  39730. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39731. /**
  39732. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39733. */
  39734. _this._useRoughnessFromMetallicTextureAlpha = true;
  39735. /**
  39736. * Specifies if the metallic texture contains the roughness information in its green channel.
  39737. */
  39738. _this._useRoughnessFromMetallicTextureGreen = false;
  39739. /**
  39740. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39741. */
  39742. _this._useMetallnessFromMetallicTextureBlue = false;
  39743. /**
  39744. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39745. */
  39746. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39747. /**
  39748. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39749. */
  39750. _this._useAmbientInGrayScale = false;
  39751. /**
  39752. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39753. * The material will try to infer what glossiness each pixel should be.
  39754. */
  39755. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39756. /**
  39757. * BJS is using an harcoded light falloff based on a manually sets up range.
  39758. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39759. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39760. */
  39761. _this._usePhysicalLightFalloff = true;
  39762. /**
  39763. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39764. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39765. */
  39766. _this._useRadianceOverAlpha = true;
  39767. /**
  39768. * Allows using the bump map in parallax mode.
  39769. */
  39770. _this._useParallax = false;
  39771. /**
  39772. * Allows using the bump map in parallax occlusion mode.
  39773. */
  39774. _this._useParallaxOcclusion = false;
  39775. /**
  39776. * Controls the scale bias of the parallax mode.
  39777. */
  39778. _this._parallaxScaleBias = 0.05;
  39779. /**
  39780. * If sets to true, disables all the lights affecting the material.
  39781. */
  39782. _this._disableLighting = false;
  39783. /**
  39784. * Number of Simultaneous lights allowed on the material.
  39785. */
  39786. _this._maxSimultaneousLights = 4;
  39787. /**
  39788. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39789. */
  39790. _this._invertNormalMapX = false;
  39791. /**
  39792. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39793. */
  39794. _this._invertNormalMapY = false;
  39795. /**
  39796. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39797. */
  39798. _this._twoSidedLighting = false;
  39799. /**
  39800. * Defines the alpha limits in alpha test mode.
  39801. */
  39802. _this._alphaCutOff = 0.4;
  39803. /**
  39804. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39805. */
  39806. _this._forceAlphaTest = false;
  39807. /**
  39808. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39809. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39810. */
  39811. _this._useAlphaFresnel = false;
  39812. /**
  39813. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39814. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39815. */
  39816. _this._useLinearAlphaFresnel = false;
  39817. /**
  39818. * The transparency mode of the material.
  39819. */
  39820. _this._transparencyMode = null;
  39821. /**
  39822. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39823. * from cos thetav and roughness:
  39824. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39825. */
  39826. _this._environmentBRDFTexture = null;
  39827. /**
  39828. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39829. */
  39830. _this._forceIrradianceInFragment = false;
  39831. /**
  39832. * Force normal to face away from face.
  39833. */
  39834. _this._forceNormalForward = false;
  39835. /**
  39836. * Force metallic workflow.
  39837. */
  39838. _this._forceMetallicWorkflow = false;
  39839. /**
  39840. * Stores the available render targets.
  39841. */
  39842. _this._renderTargets = new BABYLON.SmartArray(16);
  39843. /**
  39844. * Sets the global ambient color for the material used in lighting calculations.
  39845. */
  39846. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39847. // Setup the default processing configuration to the scene.
  39848. _this._attachImageProcessingConfiguration(null);
  39849. _this.getRenderTargetTextures = function () {
  39850. _this._renderTargets.reset();
  39851. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39852. _this._renderTargets.push(_this._reflectionTexture);
  39853. }
  39854. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39855. _this._renderTargets.push(_this._refractionTexture);
  39856. }
  39857. return _this._renderTargets;
  39858. };
  39859. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39860. return _this;
  39861. }
  39862. /**
  39863. * Attaches a new image processing configuration to the PBR Material.
  39864. * @param configuration
  39865. */
  39866. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39867. var _this = this;
  39868. if (configuration === this._imageProcessingConfiguration) {
  39869. return;
  39870. }
  39871. // Detaches observer.
  39872. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39873. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39874. }
  39875. // Pick the scene configuration if needed.
  39876. if (!configuration) {
  39877. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39878. }
  39879. else {
  39880. this._imageProcessingConfiguration = configuration;
  39881. }
  39882. // Attaches observer.
  39883. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39884. _this._markAllSubMeshesAsImageProcessingDirty();
  39885. });
  39886. };
  39887. /**
  39888. * Gets the name of the material class.
  39889. */
  39890. PBRBaseMaterial.prototype.getClassName = function () {
  39891. return "PBRBaseMaterial";
  39892. };
  39893. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  39894. /**
  39895. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39896. */
  39897. get: function () {
  39898. return this._useLogarithmicDepth;
  39899. },
  39900. /**
  39901. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39902. */
  39903. set: function (value) {
  39904. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39905. },
  39906. enumerable: true,
  39907. configurable: true
  39908. });
  39909. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  39910. /**
  39911. * Gets the current transparency mode.
  39912. */
  39913. get: function () {
  39914. return this._transparencyMode;
  39915. },
  39916. /**
  39917. * Sets the transparency mode of the material.
  39918. */
  39919. set: function (value) {
  39920. if (this._transparencyMode === value) {
  39921. return;
  39922. }
  39923. this._transparencyMode = value;
  39924. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  39925. this._markAllSubMeshesAsTexturesAndMiscDirty();
  39926. },
  39927. enumerable: true,
  39928. configurable: true
  39929. });
  39930. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  39931. /**
  39932. * Returns true if alpha blending should be disabled.
  39933. */
  39934. get: function () {
  39935. return (this._linkRefractionWithTransparency ||
  39936. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  39937. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39938. },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. /**
  39943. * Specifies whether or not this material should be rendered in alpha blend mode.
  39944. */
  39945. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  39946. if (this._disableAlphaBlending) {
  39947. return false;
  39948. }
  39949. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  39950. };
  39951. /**
  39952. * Specifies if the mesh will require alpha blending.
  39953. * @param mesh - BJS mesh.
  39954. */
  39955. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  39956. if (this._disableAlphaBlending) {
  39957. return false;
  39958. }
  39959. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  39960. };
  39961. /**
  39962. * Specifies whether or not this material should be rendered in alpha test mode.
  39963. */
  39964. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  39965. if (this._forceAlphaTest) {
  39966. return true;
  39967. }
  39968. if (this._linkRefractionWithTransparency) {
  39969. return false;
  39970. }
  39971. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39972. };
  39973. /**
  39974. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  39975. */
  39976. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39977. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39978. };
  39979. /**
  39980. * Gets the texture used for the alpha test.
  39981. */
  39982. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  39983. return this._albedoTexture;
  39984. };
  39985. /**
  39986. * Specifies that the submesh is ready to be used.
  39987. * @param mesh - BJS mesh.
  39988. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  39989. * @param useInstances - Specifies that instances should be used.
  39990. * @returns - boolean indicating that the submesh is ready or not.
  39991. */
  39992. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39993. if (subMesh.effect && this.isFrozen) {
  39994. if (this._wasPreviouslyReady) {
  39995. return true;
  39996. }
  39997. }
  39998. if (!subMesh._materialDefines) {
  39999. subMesh._materialDefines = new PBRMaterialDefines();
  40000. }
  40001. var defines = subMesh._materialDefines;
  40002. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40003. if (defines._renderId === this.getScene().getRenderId()) {
  40004. return true;
  40005. }
  40006. }
  40007. var scene = this.getScene();
  40008. var engine = scene.getEngine();
  40009. if (defines._areTexturesDirty) {
  40010. if (scene.texturesEnabled) {
  40011. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40012. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40013. return false;
  40014. }
  40015. }
  40016. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40017. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40018. return false;
  40019. }
  40020. }
  40021. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40022. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40023. return false;
  40024. }
  40025. }
  40026. var reflectionTexture = this._getReflectionTexture();
  40027. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40028. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40029. return false;
  40030. }
  40031. }
  40032. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40033. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40034. return false;
  40035. }
  40036. }
  40037. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40038. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40039. return false;
  40040. }
  40041. }
  40042. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40043. if (this._metallicTexture) {
  40044. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40045. return false;
  40046. }
  40047. }
  40048. else if (this._reflectivityTexture) {
  40049. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40050. return false;
  40051. }
  40052. }
  40053. if (this._microSurfaceTexture) {
  40054. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40055. return false;
  40056. }
  40057. }
  40058. }
  40059. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40060. // Bump texture cannot be not blocking.
  40061. if (!this._bumpTexture.isReady()) {
  40062. return false;
  40063. }
  40064. }
  40065. var refractionTexture = this._getRefractionTexture();
  40066. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40067. if (!refractionTexture.isReadyOrNotBlocking()) {
  40068. return false;
  40069. }
  40070. }
  40071. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40072. // This is blocking.
  40073. if (!this._environmentBRDFTexture.isReady()) {
  40074. return false;
  40075. }
  40076. }
  40077. }
  40078. }
  40079. if (defines._areImageProcessingDirty) {
  40080. if (!this._imageProcessingConfiguration.isReady()) {
  40081. return false;
  40082. }
  40083. }
  40084. if (!engine.getCaps().standardDerivatives) {
  40085. var bufferMesh = null;
  40086. if (mesh.getClassName() === "InstancedMesh") {
  40087. bufferMesh = mesh.sourceMesh;
  40088. }
  40089. else if (mesh.getClassName() === "Mesh") {
  40090. bufferMesh = mesh;
  40091. }
  40092. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40093. bufferMesh.createNormals(true);
  40094. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40095. }
  40096. }
  40097. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40098. if (effect) {
  40099. scene.resetCachedMaterial();
  40100. subMesh.setEffect(effect, defines);
  40101. this.buildUniformLayout();
  40102. }
  40103. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40104. return false;
  40105. }
  40106. defines._renderId = scene.getRenderId();
  40107. this._wasPreviouslyReady = true;
  40108. return true;
  40109. };
  40110. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40111. if (onCompiled === void 0) { onCompiled = null; }
  40112. if (onError === void 0) { onError = null; }
  40113. if (useInstances === void 0) { useInstances = null; }
  40114. if (useClipPlane === void 0) { useClipPlane = null; }
  40115. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40116. if (!defines.isDirty) {
  40117. return null;
  40118. }
  40119. defines.markAsProcessed();
  40120. var scene = this.getScene();
  40121. var engine = scene.getEngine();
  40122. // Fallbacks
  40123. var fallbacks = new BABYLON.EffectFallbacks();
  40124. var fallbackRank = 0;
  40125. if (defines.USESPHERICALINVERTEX) {
  40126. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40127. }
  40128. if (defines.FOG) {
  40129. fallbacks.addFallback(fallbackRank, "FOG");
  40130. }
  40131. if (defines.POINTSIZE) {
  40132. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40133. }
  40134. if (defines.LOGARITHMICDEPTH) {
  40135. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40136. }
  40137. if (defines.PARALLAX) {
  40138. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40139. }
  40140. if (defines.PARALLAXOCCLUSION) {
  40141. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40142. }
  40143. if (defines.ENVIRONMENTBRDF) {
  40144. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40145. }
  40146. if (defines.TANGENT) {
  40147. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40148. }
  40149. if (defines.BUMP) {
  40150. fallbacks.addFallback(fallbackRank++, "BUMP");
  40151. }
  40152. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40153. if (defines.SPECULARTERM) {
  40154. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40155. }
  40156. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40157. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40158. }
  40159. if (defines.LIGHTMAP) {
  40160. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40161. }
  40162. if (defines.NORMAL) {
  40163. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40164. }
  40165. if (defines.AMBIENT) {
  40166. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40167. }
  40168. if (defines.EMISSIVE) {
  40169. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40170. }
  40171. if (defines.VERTEXCOLOR) {
  40172. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40173. }
  40174. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40175. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40176. }
  40177. if (defines.MORPHTARGETS) {
  40178. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40179. }
  40180. //Attributes
  40181. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40182. if (defines.NORMAL) {
  40183. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40184. }
  40185. if (defines.TANGENT) {
  40186. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40187. }
  40188. if (defines.UV1) {
  40189. attribs.push(BABYLON.VertexBuffer.UVKind);
  40190. }
  40191. if (defines.UV2) {
  40192. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40193. }
  40194. if (defines.VERTEXCOLOR) {
  40195. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40196. }
  40197. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40198. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40199. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40200. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40201. "vFogInfos", "vFogColor", "pointSize",
  40202. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40203. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40204. "mBones",
  40205. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40206. "vLightingIntensity",
  40207. "logarithmicDepthConstant",
  40208. "vSphericalX", "vSphericalY", "vSphericalZ",
  40209. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40210. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40211. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40212. "vTangentSpaceParams"
  40213. ];
  40214. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40215. "bumpSampler", "lightmapSampler", "opacitySampler",
  40216. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40217. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40218. "microSurfaceSampler", "environmentBrdfSampler"];
  40219. var uniformBuffers = ["Material", "Scene"];
  40220. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40221. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40222. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40223. uniformsNames: uniforms,
  40224. uniformBuffersNames: uniformBuffers,
  40225. samplers: samplers,
  40226. defines: defines,
  40227. maxSimultaneousLights: this._maxSimultaneousLights
  40228. });
  40229. var join = defines.toString();
  40230. return engine.createEffect("pbr", {
  40231. attributes: attribs,
  40232. uniformsNames: uniforms,
  40233. uniformBuffersNames: uniformBuffers,
  40234. samplers: samplers,
  40235. defines: join,
  40236. fallbacks: fallbacks,
  40237. onCompiled: onCompiled,
  40238. onError: onError,
  40239. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40240. }, engine);
  40241. };
  40242. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40243. if (useInstances === void 0) { useInstances = null; }
  40244. if (useClipPlane === void 0) { useClipPlane = null; }
  40245. var scene = this.getScene();
  40246. var engine = scene.getEngine();
  40247. // Lights
  40248. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40249. defines._needNormals = true;
  40250. // Textures
  40251. if (defines._areTexturesDirty) {
  40252. defines._needUVs = false;
  40253. if (scene.texturesEnabled) {
  40254. if (scene.getEngine().getCaps().textureLOD) {
  40255. defines.LODBASEDMICROSFURACE = true;
  40256. }
  40257. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40259. }
  40260. else {
  40261. defines.ALBEDO = false;
  40262. }
  40263. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40265. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40266. }
  40267. else {
  40268. defines.AMBIENT = false;
  40269. }
  40270. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40272. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40273. }
  40274. else {
  40275. defines.OPACITY = false;
  40276. }
  40277. var reflectionTexture = this._getReflectionTexture();
  40278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40279. defines.REFLECTION = true;
  40280. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40281. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40282. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40283. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40284. defines.INVERTCUBICMAP = true;
  40285. }
  40286. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40287. switch (reflectionTexture.coordinatesMode) {
  40288. case BABYLON.Texture.CUBIC_MODE:
  40289. case BABYLON.Texture.INVCUBIC_MODE:
  40290. defines.REFLECTIONMAP_CUBIC = true;
  40291. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40292. break;
  40293. case BABYLON.Texture.EXPLICIT_MODE:
  40294. defines.REFLECTIONMAP_EXPLICIT = true;
  40295. break;
  40296. case BABYLON.Texture.PLANAR_MODE:
  40297. defines.REFLECTIONMAP_PLANAR = true;
  40298. break;
  40299. case BABYLON.Texture.PROJECTION_MODE:
  40300. defines.REFLECTIONMAP_PROJECTION = true;
  40301. break;
  40302. case BABYLON.Texture.SKYBOX_MODE:
  40303. defines.REFLECTIONMAP_SKYBOX = true;
  40304. break;
  40305. case BABYLON.Texture.SPHERICAL_MODE:
  40306. defines.REFLECTIONMAP_SPHERICAL = true;
  40307. break;
  40308. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40309. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40310. break;
  40311. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40312. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40313. break;
  40314. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40315. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40316. break;
  40317. }
  40318. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40319. if (reflectionTexture.sphericalPolynomial) {
  40320. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40321. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40322. defines.USESPHERICALINVERTEX = false;
  40323. }
  40324. else {
  40325. defines.USESPHERICALINVERTEX = true;
  40326. }
  40327. }
  40328. }
  40329. }
  40330. else {
  40331. defines.REFLECTION = false;
  40332. defines.REFLECTIONMAP_3D = false;
  40333. defines.REFLECTIONMAP_SPHERICAL = false;
  40334. defines.REFLECTIONMAP_PLANAR = false;
  40335. defines.REFLECTIONMAP_CUBIC = false;
  40336. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40337. defines.REFLECTIONMAP_PROJECTION = false;
  40338. defines.REFLECTIONMAP_SKYBOX = false;
  40339. defines.REFLECTIONMAP_EXPLICIT = false;
  40340. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40341. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40342. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40343. defines.INVERTCUBICMAP = false;
  40344. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40345. defines.USESPHERICALINVERTEX = false;
  40346. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40347. defines.LODINREFLECTIONALPHA = false;
  40348. defines.GAMMAREFLECTION = false;
  40349. }
  40350. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40352. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40353. }
  40354. else {
  40355. defines.LIGHTMAP = false;
  40356. }
  40357. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40359. }
  40360. else {
  40361. defines.EMISSIVE = false;
  40362. }
  40363. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40364. if (this._metallicTexture) {
  40365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40366. defines.METALLICWORKFLOW = true;
  40367. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40368. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40369. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40370. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40371. }
  40372. else if (this._reflectivityTexture) {
  40373. defines.METALLICWORKFLOW = false;
  40374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40375. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40376. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40377. }
  40378. else {
  40379. defines.METALLICWORKFLOW = false;
  40380. defines.REFLECTIVITY = false;
  40381. }
  40382. if (this._microSurfaceTexture) {
  40383. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40384. }
  40385. else {
  40386. defines.MICROSURFACEMAP = false;
  40387. }
  40388. }
  40389. else {
  40390. defines.REFLECTIVITY = false;
  40391. defines.MICROSURFACEMAP = false;
  40392. }
  40393. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40394. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40395. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40396. defines.PARALLAX = true;
  40397. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40398. }
  40399. else {
  40400. defines.PARALLAX = false;
  40401. }
  40402. }
  40403. else {
  40404. defines.BUMP = false;
  40405. }
  40406. var refractionTexture = this._getRefractionTexture();
  40407. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40408. defines.REFRACTION = true;
  40409. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40410. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40411. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40412. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40413. if (this._linkRefractionWithTransparency) {
  40414. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40415. }
  40416. }
  40417. else {
  40418. defines.REFRACTION = false;
  40419. }
  40420. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40421. defines.ENVIRONMENTBRDF = true;
  40422. }
  40423. else {
  40424. defines.ENVIRONMENTBRDF = false;
  40425. }
  40426. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40427. defines.ALPHAFROMALBEDO = true;
  40428. }
  40429. else {
  40430. defines.ALPHAFROMALBEDO = false;
  40431. }
  40432. }
  40433. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40434. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40435. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40436. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40437. defines.METALLICWORKFLOW = true;
  40438. }
  40439. else {
  40440. defines.METALLICWORKFLOW = false;
  40441. }
  40442. if (!this.backFaceCulling && this._twoSidedLighting) {
  40443. defines.TWOSIDEDLIGHTING = true;
  40444. }
  40445. else {
  40446. defines.TWOSIDEDLIGHTING = false;
  40447. }
  40448. defines.ALPHATESTVALUE = this._alphaCutOff;
  40449. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40450. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40451. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40452. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40453. }
  40454. if (defines._areImageProcessingDirty) {
  40455. this._imageProcessingConfiguration.prepareDefines(defines);
  40456. }
  40457. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40458. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40459. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40460. // Misc.
  40461. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40462. // Values that need to be evaluated on every frame
  40463. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40464. // Attribs
  40465. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40466. };
  40467. /**
  40468. * Force shader compilation
  40469. */
  40470. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40471. var _this = this;
  40472. var localOptions = __assign({ clipPlane: false }, options);
  40473. var defines = new PBRMaterialDefines();
  40474. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40475. if (effect.isReady()) {
  40476. if (onCompiled) {
  40477. onCompiled(this);
  40478. }
  40479. }
  40480. else {
  40481. effect.onCompileObservable.add(function () {
  40482. if (onCompiled) {
  40483. onCompiled(_this);
  40484. }
  40485. });
  40486. }
  40487. };
  40488. /**
  40489. * Initializes the uniform buffer layout for the shader.
  40490. */
  40491. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40492. // Order is important !
  40493. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40494. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40495. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40496. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40497. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40498. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40499. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40500. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40501. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40502. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40503. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40504. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40505. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40506. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40507. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40508. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40509. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40510. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40511. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40512. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40513. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40514. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40515. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40516. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40517. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40518. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40519. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40520. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40521. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40522. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40523. this._uniformBuffer.addUniform("pointSize", 1);
  40524. this._uniformBuffer.create();
  40525. };
  40526. /**
  40527. * Unbinds the textures.
  40528. */
  40529. PBRBaseMaterial.prototype.unbind = function () {
  40530. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40531. this._uniformBuffer.setTexture("reflectionSampler", null);
  40532. }
  40533. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40534. this._uniformBuffer.setTexture("refractionSampler", null);
  40535. }
  40536. _super.prototype.unbind.call(this);
  40537. };
  40538. /**
  40539. * Binds to the world matrix.
  40540. * @param world - The world matrix.
  40541. */
  40542. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40543. this._activeEffect.setMatrix("world", world);
  40544. };
  40545. /**
  40546. * Binds the submesh data.
  40547. * @param world - The world matrix.
  40548. * @param mesh - The BJS mesh.
  40549. * @param subMesh - A submesh of the BJS mesh.
  40550. */
  40551. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40552. var scene = this.getScene();
  40553. var defines = subMesh._materialDefines;
  40554. if (!defines) {
  40555. return;
  40556. }
  40557. var effect = subMesh.effect;
  40558. if (!effect) {
  40559. return;
  40560. }
  40561. this._activeEffect = effect;
  40562. // Matrices
  40563. this.bindOnlyWorldMatrix(world);
  40564. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40565. // Bones
  40566. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40567. var reflectionTexture = null;
  40568. if (mustRebind) {
  40569. this._uniformBuffer.bindToEffect(effect, "Material");
  40570. this.bindViewProjection(effect);
  40571. reflectionTexture = this._getReflectionTexture();
  40572. var refractionTexture = this._getRefractionTexture();
  40573. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40574. // Texture uniforms
  40575. if (scene.texturesEnabled) {
  40576. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40577. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40578. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40579. }
  40580. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40581. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40582. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40583. }
  40584. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40585. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40586. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40587. }
  40588. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40589. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40590. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40591. if (reflectionTexture.boundingBoxSize) {
  40592. var cubeTexture = reflectionTexture;
  40593. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40594. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40595. }
  40596. var polynomials = reflectionTexture.sphericalPolynomial;
  40597. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40598. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40599. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40600. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40601. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40602. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40603. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40604. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40605. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40606. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40607. }
  40608. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40609. }
  40610. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40611. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40612. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40613. }
  40614. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40615. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40616. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40617. }
  40618. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40619. if (this._metallicTexture) {
  40620. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40621. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40622. }
  40623. else if (this._reflectivityTexture) {
  40624. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40625. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40626. }
  40627. if (this._microSurfaceTexture) {
  40628. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40629. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40630. }
  40631. }
  40632. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40633. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40634. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40635. if (scene._mirroredCameraPosition) {
  40636. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40637. }
  40638. else {
  40639. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40640. }
  40641. }
  40642. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40643. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40644. var depth = 1.0;
  40645. if (!refractionTexture.isCube) {
  40646. if (refractionTexture.depth) {
  40647. depth = refractionTexture.depth;
  40648. }
  40649. }
  40650. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40651. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40652. }
  40653. }
  40654. // Point size
  40655. if (this.pointsCloud) {
  40656. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40657. }
  40658. // Colors
  40659. if (defines.METALLICWORKFLOW) {
  40660. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40661. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40662. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40663. }
  40664. else {
  40665. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40666. }
  40667. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40668. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40669. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40670. // Misc
  40671. this._lightingInfos.x = this._directIntensity;
  40672. this._lightingInfos.y = this._emissiveIntensity;
  40673. this._lightingInfos.z = this._environmentIntensity;
  40674. this._lightingInfos.w = this._specularIntensity;
  40675. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40676. }
  40677. // Textures
  40678. if (scene.texturesEnabled) {
  40679. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40680. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40681. }
  40682. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40683. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40684. }
  40685. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40686. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40687. }
  40688. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40689. if (defines.LODBASEDMICROSFURACE) {
  40690. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40691. }
  40692. else {
  40693. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40694. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40695. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40696. }
  40697. }
  40698. if (defines.ENVIRONMENTBRDF) {
  40699. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40700. }
  40701. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40702. if (defines.LODBASEDMICROSFURACE) {
  40703. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40704. }
  40705. else {
  40706. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40707. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40708. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40709. }
  40710. }
  40711. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40712. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40713. }
  40714. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40715. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40716. }
  40717. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40718. if (this._metallicTexture) {
  40719. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40720. }
  40721. else if (this._reflectivityTexture) {
  40722. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40723. }
  40724. if (this._microSurfaceTexture) {
  40725. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40726. }
  40727. }
  40728. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40729. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40730. }
  40731. }
  40732. // Clip plane
  40733. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40734. // Colors
  40735. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40736. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40737. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40738. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40739. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40740. }
  40741. if (mustRebind || !this.isFrozen) {
  40742. // Lights
  40743. if (scene.lightsEnabled && !this._disableLighting) {
  40744. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40745. }
  40746. // View
  40747. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40748. this.bindView(effect);
  40749. }
  40750. // Fog
  40751. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40752. // Morph targets
  40753. if (defines.NUM_MORPH_INFLUENCERS) {
  40754. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40755. }
  40756. // image processing
  40757. this._imageProcessingConfiguration.bind(this._activeEffect);
  40758. // Log. depth
  40759. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40760. }
  40761. this._uniformBuffer.update();
  40762. this._afterBind(mesh);
  40763. };
  40764. /**
  40765. * Returns the animatable textures.
  40766. * @returns - Array of animatable textures.
  40767. */
  40768. PBRBaseMaterial.prototype.getAnimatables = function () {
  40769. var results = [];
  40770. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40771. results.push(this._albedoTexture);
  40772. }
  40773. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40774. results.push(this._ambientTexture);
  40775. }
  40776. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40777. results.push(this._opacityTexture);
  40778. }
  40779. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40780. results.push(this._reflectionTexture);
  40781. }
  40782. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40783. results.push(this._emissiveTexture);
  40784. }
  40785. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40786. results.push(this._metallicTexture);
  40787. }
  40788. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40789. results.push(this._reflectivityTexture);
  40790. }
  40791. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40792. results.push(this._bumpTexture);
  40793. }
  40794. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40795. results.push(this._lightmapTexture);
  40796. }
  40797. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40798. results.push(this._refractionTexture);
  40799. }
  40800. return results;
  40801. };
  40802. /**
  40803. * Returns the texture used for reflections.
  40804. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40805. */
  40806. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40807. if (this._reflectionTexture) {
  40808. return this._reflectionTexture;
  40809. }
  40810. return this.getScene().environmentTexture;
  40811. };
  40812. /**
  40813. * Returns the texture used for refraction or null if none is used.
  40814. * @returns - Refection texture if present. If no refraction texture and refraction
  40815. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40816. */
  40817. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40818. if (this._refractionTexture) {
  40819. return this._refractionTexture;
  40820. }
  40821. if (this._linkRefractionWithTransparency) {
  40822. return this.getScene().environmentTexture;
  40823. }
  40824. return null;
  40825. };
  40826. /**
  40827. * Disposes the resources of the material.
  40828. * @param forceDisposeEffect - Forces the disposal of effects.
  40829. * @param forceDisposeTextures - Forces the disposal of all textures.
  40830. */
  40831. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40832. if (forceDisposeTextures) {
  40833. if (this._albedoTexture) {
  40834. this._albedoTexture.dispose();
  40835. }
  40836. if (this._ambientTexture) {
  40837. this._ambientTexture.dispose();
  40838. }
  40839. if (this._opacityTexture) {
  40840. this._opacityTexture.dispose();
  40841. }
  40842. if (this._reflectionTexture) {
  40843. this._reflectionTexture.dispose();
  40844. }
  40845. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40846. this._environmentBRDFTexture.dispose();
  40847. }
  40848. if (this._emissiveTexture) {
  40849. this._emissiveTexture.dispose();
  40850. }
  40851. if (this._metallicTexture) {
  40852. this._metallicTexture.dispose();
  40853. }
  40854. if (this._reflectivityTexture) {
  40855. this._reflectivityTexture.dispose();
  40856. }
  40857. if (this._bumpTexture) {
  40858. this._bumpTexture.dispose();
  40859. }
  40860. if (this._lightmapTexture) {
  40861. this._lightmapTexture.dispose();
  40862. }
  40863. if (this._refractionTexture) {
  40864. this._refractionTexture.dispose();
  40865. }
  40866. }
  40867. this._renderTargets.dispose();
  40868. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40869. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40870. }
  40871. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40872. };
  40873. /**
  40874. * Stores the reflectivity values based on metallic roughness workflow.
  40875. */
  40876. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40877. __decorate([
  40878. BABYLON.serializeAsImageProcessingConfiguration()
  40879. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40880. __decorate([
  40881. BABYLON.serialize()
  40882. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40883. __decorate([
  40884. BABYLON.serialize()
  40885. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40886. return PBRBaseMaterial;
  40887. }(BABYLON.PushMaterial));
  40888. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40889. })(BABYLON || (BABYLON = {}));
  40890. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  40891. var BABYLON;
  40892. (function (BABYLON) {
  40893. /**
  40894. * The Physically based simple base material of BJS.
  40895. *
  40896. * This enables better naming and convention enforcements on top of the pbrMaterial.
  40897. * It is used as the base class for both the specGloss and metalRough conventions.
  40898. */
  40899. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  40900. __extends(PBRBaseSimpleMaterial, _super);
  40901. /**
  40902. * Instantiates a new PBRMaterial instance.
  40903. *
  40904. * @param name The material name
  40905. * @param scene The scene the material will be use in.
  40906. */
  40907. function PBRBaseSimpleMaterial(name, scene) {
  40908. var _this = _super.call(this, name, scene) || this;
  40909. /**
  40910. * Number of Simultaneous lights allowed on the material.
  40911. */
  40912. _this.maxSimultaneousLights = 4;
  40913. /**
  40914. * If sets to true, disables all the lights affecting the material.
  40915. */
  40916. _this.disableLighting = false;
  40917. /**
  40918. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40919. */
  40920. _this.invertNormalMapX = false;
  40921. /**
  40922. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40923. */
  40924. _this.invertNormalMapY = false;
  40925. /**
  40926. * Emissivie color used to self-illuminate the model.
  40927. */
  40928. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40929. /**
  40930. * Occlusion Channel Strenght.
  40931. */
  40932. _this.occlusionStrength = 1.0;
  40933. _this.useLightmapAsShadowmap = false;
  40934. _this._useAlphaFromAlbedoTexture = true;
  40935. _this._useAmbientInGrayScale = true;
  40936. return _this;
  40937. }
  40938. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  40939. /**
  40940. * Gets the current double sided mode.
  40941. */
  40942. get: function () {
  40943. return this._twoSidedLighting;
  40944. },
  40945. /**
  40946. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40947. */
  40948. set: function (value) {
  40949. if (this._twoSidedLighting === value) {
  40950. return;
  40951. }
  40952. this._twoSidedLighting = value;
  40953. this.backFaceCulling = !value;
  40954. this._markAllSubMeshesAsTexturesDirty();
  40955. },
  40956. enumerable: true,
  40957. configurable: true
  40958. });
  40959. /**
  40960. * Return the active textures of the material.
  40961. */
  40962. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  40963. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40964. if (this.environmentTexture) {
  40965. activeTextures.push(this.environmentTexture);
  40966. }
  40967. if (this.normalTexture) {
  40968. activeTextures.push(this.normalTexture);
  40969. }
  40970. if (this.emissiveTexture) {
  40971. activeTextures.push(this.emissiveTexture);
  40972. }
  40973. if (this.occlusionTexture) {
  40974. activeTextures.push(this.occlusionTexture);
  40975. }
  40976. if (this.lightmapTexture) {
  40977. activeTextures.push(this.lightmapTexture);
  40978. }
  40979. return activeTextures;
  40980. };
  40981. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  40982. if (_super.prototype.hasTexture.call(this, texture)) {
  40983. return true;
  40984. }
  40985. if (this.lightmapTexture === texture) {
  40986. return true;
  40987. }
  40988. return false;
  40989. };
  40990. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  40991. return "PBRBaseSimpleMaterial";
  40992. };
  40993. __decorate([
  40994. BABYLON.serialize(),
  40995. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40996. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  40997. __decorate([
  40998. BABYLON.serialize(),
  40999. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41000. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41001. __decorate([
  41002. BABYLON.serializeAsTexture(),
  41003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41004. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41005. __decorate([
  41006. BABYLON.serialize(),
  41007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41008. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41009. __decorate([
  41010. BABYLON.serialize(),
  41011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41012. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41013. __decorate([
  41014. BABYLON.serializeAsTexture(),
  41015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41016. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41017. __decorate([
  41018. BABYLON.serializeAsColor3("emissive"),
  41019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41020. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41021. __decorate([
  41022. BABYLON.serializeAsTexture(),
  41023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41024. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41025. __decorate([
  41026. BABYLON.serialize(),
  41027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41028. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41029. __decorate([
  41030. BABYLON.serializeAsTexture(),
  41031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41032. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41033. __decorate([
  41034. BABYLON.serialize(),
  41035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41036. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41037. __decorate([
  41038. BABYLON.serialize()
  41039. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41040. __decorate([
  41041. BABYLON.serializeAsTexture(),
  41042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41043. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41044. __decorate([
  41045. BABYLON.serialize(),
  41046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41047. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41048. return PBRBaseSimpleMaterial;
  41049. }(BABYLON.PBRBaseMaterial));
  41050. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41051. })(BABYLON || (BABYLON = {}));
  41052. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41053. var BABYLON;
  41054. (function (BABYLON) {
  41055. /**
  41056. * The Physically based material of BJS.
  41057. *
  41058. * This offers the main features of a standard PBR material.
  41059. * For more information, please refer to the documentation :
  41060. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41061. */
  41062. var PBRMaterial = /** @class */ (function (_super) {
  41063. __extends(PBRMaterial, _super);
  41064. /**
  41065. * Instantiates a new PBRMaterial instance.
  41066. *
  41067. * @param name The material name
  41068. * @param scene The scene the material will be use in.
  41069. */
  41070. function PBRMaterial(name, scene) {
  41071. var _this = _super.call(this, name, scene) || this;
  41072. /**
  41073. * Intensity of the direct lights e.g. the four lights available in your scene.
  41074. * This impacts both the direct diffuse and specular highlights.
  41075. */
  41076. _this.directIntensity = 1.0;
  41077. /**
  41078. * Intensity of the emissive part of the material.
  41079. * This helps controlling the emissive effect without modifying the emissive color.
  41080. */
  41081. _this.emissiveIntensity = 1.0;
  41082. /**
  41083. * Intensity of the environment e.g. how much the environment will light the object
  41084. * either through harmonics for rough material or through the refelction for shiny ones.
  41085. */
  41086. _this.environmentIntensity = 1.0;
  41087. /**
  41088. * This is a special control allowing the reduction of the specular highlights coming from the
  41089. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41090. */
  41091. _this.specularIntensity = 1.0;
  41092. /**
  41093. * Debug Control allowing disabling the bump map on this material.
  41094. */
  41095. _this.disableBumpMap = false;
  41096. /**
  41097. * AKA Occlusion Texture Intensity in other nomenclature.
  41098. */
  41099. _this.ambientTextureStrength = 1.0;
  41100. /**
  41101. * The color of a material in ambient lighting.
  41102. */
  41103. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41104. /**
  41105. * AKA Diffuse Color in other nomenclature.
  41106. */
  41107. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41108. /**
  41109. * AKA Specular Color in other nomenclature.
  41110. */
  41111. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41112. /**
  41113. * The color reflected from the material.
  41114. */
  41115. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41116. /**
  41117. * The color emitted from the material.
  41118. */
  41119. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41120. /**
  41121. * AKA Glossiness in other nomenclature.
  41122. */
  41123. _this.microSurface = 1.0;
  41124. /**
  41125. * source material index of refraction (IOR)' / 'destination material IOR.
  41126. */
  41127. _this.indexOfRefraction = 0.66;
  41128. /**
  41129. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41130. */
  41131. _this.invertRefractionY = false;
  41132. /**
  41133. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41134. * Materials half opaque for instance using refraction could benefit from this control.
  41135. */
  41136. _this.linkRefractionWithTransparency = false;
  41137. _this.useLightmapAsShadowmap = false;
  41138. /**
  41139. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41140. */
  41141. _this.useAlphaFromAlbedoTexture = false;
  41142. /**
  41143. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41144. */
  41145. _this.forceAlphaTest = false;
  41146. /**
  41147. * Defines the alpha limits in alpha test mode.
  41148. */
  41149. _this.alphaCutOff = 0.4;
  41150. /**
  41151. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41152. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41153. */
  41154. _this.useSpecularOverAlpha = true;
  41155. /**
  41156. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41157. */
  41158. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41159. /**
  41160. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41161. */
  41162. _this.useRoughnessFromMetallicTextureAlpha = true;
  41163. /**
  41164. * Specifies if the metallic texture contains the roughness information in its green channel.
  41165. */
  41166. _this.useRoughnessFromMetallicTextureGreen = false;
  41167. /**
  41168. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41169. */
  41170. _this.useMetallnessFromMetallicTextureBlue = false;
  41171. /**
  41172. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41173. */
  41174. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41175. /**
  41176. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41177. */
  41178. _this.useAmbientInGrayScale = false;
  41179. /**
  41180. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41181. * The material will try to infer what glossiness each pixel should be.
  41182. */
  41183. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41184. /**
  41185. * BJS is using an harcoded light falloff based on a manually sets up range.
  41186. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41187. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41188. */
  41189. _this.usePhysicalLightFalloff = true;
  41190. /**
  41191. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41192. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41193. */
  41194. _this.useRadianceOverAlpha = true;
  41195. /**
  41196. * Allows using the bump map in parallax mode.
  41197. */
  41198. _this.useParallax = false;
  41199. /**
  41200. * Allows using the bump map in parallax occlusion mode.
  41201. */
  41202. _this.useParallaxOcclusion = false;
  41203. /**
  41204. * Controls the scale bias of the parallax mode.
  41205. */
  41206. _this.parallaxScaleBias = 0.05;
  41207. /**
  41208. * If sets to true, disables all the lights affecting the material.
  41209. */
  41210. _this.disableLighting = false;
  41211. /**
  41212. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41213. */
  41214. _this.forceIrradianceInFragment = false;
  41215. /**
  41216. * Number of Simultaneous lights allowed on the material.
  41217. */
  41218. _this.maxSimultaneousLights = 4;
  41219. /**
  41220. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41221. */
  41222. _this.invertNormalMapX = false;
  41223. /**
  41224. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41225. */
  41226. _this.invertNormalMapY = false;
  41227. /**
  41228. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41229. */
  41230. _this.twoSidedLighting = false;
  41231. /**
  41232. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41233. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41234. */
  41235. _this.useAlphaFresnel = false;
  41236. /**
  41237. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41238. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41239. */
  41240. _this.useLinearAlphaFresnel = false;
  41241. /**
  41242. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41243. * And/Or occlude the blended part.
  41244. */
  41245. _this.environmentBRDFTexture = null;
  41246. /**
  41247. * Force normal to face away from face.
  41248. */
  41249. _this.forceNormalForward = false;
  41250. /**
  41251. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41252. * makes the reflect vector face the model (under horizon).
  41253. */
  41254. _this.useHorizonOcclusion = true;
  41255. /**
  41256. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41257. * too much the area relying on ambient texture to define their ambient occlusion.
  41258. */
  41259. _this.useRadianceOcclusion = true;
  41260. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41261. return _this;
  41262. }
  41263. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41264. /**
  41265. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41266. */
  41267. get: function () {
  41268. return this._PBRMATERIAL_OPAQUE;
  41269. },
  41270. enumerable: true,
  41271. configurable: true
  41272. });
  41273. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41274. /**
  41275. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41276. */
  41277. get: function () {
  41278. return this._PBRMATERIAL_ALPHATEST;
  41279. },
  41280. enumerable: true,
  41281. configurable: true
  41282. });
  41283. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41284. /**
  41285. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41286. */
  41287. get: function () {
  41288. return this._PBRMATERIAL_ALPHABLEND;
  41289. },
  41290. enumerable: true,
  41291. configurable: true
  41292. });
  41293. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41294. /**
  41295. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41296. * They are also discarded below the alpha cutoff threshold to improve performances.
  41297. */
  41298. get: function () {
  41299. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41300. },
  41301. enumerable: true,
  41302. configurable: true
  41303. });
  41304. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41305. /**
  41306. * Gets the image processing configuration used either in this material.
  41307. */
  41308. get: function () {
  41309. return this._imageProcessingConfiguration;
  41310. },
  41311. /**
  41312. * Sets the Default image processing configuration used either in the this material.
  41313. *
  41314. * If sets to null, the scene one is in use.
  41315. */
  41316. set: function (value) {
  41317. this._attachImageProcessingConfiguration(value);
  41318. // Ensure the effect will be rebuilt.
  41319. this._markAllSubMeshesAsTexturesDirty();
  41320. },
  41321. enumerable: true,
  41322. configurable: true
  41323. });
  41324. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41325. /**
  41326. * Gets wether the color curves effect is enabled.
  41327. */
  41328. get: function () {
  41329. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41330. },
  41331. /**
  41332. * Sets wether the color curves effect is enabled.
  41333. */
  41334. set: function (value) {
  41335. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41341. /**
  41342. * Gets wether the color grading effect is enabled.
  41343. */
  41344. get: function () {
  41345. return this.imageProcessingConfiguration.colorGradingEnabled;
  41346. },
  41347. /**
  41348. * Gets wether the color grading effect is enabled.
  41349. */
  41350. set: function (value) {
  41351. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41357. /**
  41358. * Gets wether tonemapping is enabled or not.
  41359. */
  41360. get: function () {
  41361. return this._imageProcessingConfiguration.toneMappingEnabled;
  41362. },
  41363. /**
  41364. * Sets wether tonemapping is enabled or not
  41365. */
  41366. set: function (value) {
  41367. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41368. },
  41369. enumerable: true,
  41370. configurable: true
  41371. });
  41372. ;
  41373. ;
  41374. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41375. /**
  41376. * The camera exposure used on this material.
  41377. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41378. * This corresponds to a photographic exposure.
  41379. */
  41380. get: function () {
  41381. return this._imageProcessingConfiguration.exposure;
  41382. },
  41383. /**
  41384. * The camera exposure used on this material.
  41385. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41386. * This corresponds to a photographic exposure.
  41387. */
  41388. set: function (value) {
  41389. this._imageProcessingConfiguration.exposure = value;
  41390. },
  41391. enumerable: true,
  41392. configurable: true
  41393. });
  41394. ;
  41395. ;
  41396. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41397. /**
  41398. * Gets The camera contrast used on this material.
  41399. */
  41400. get: function () {
  41401. return this._imageProcessingConfiguration.contrast;
  41402. },
  41403. /**
  41404. * Sets The camera contrast used on this material.
  41405. */
  41406. set: function (value) {
  41407. this._imageProcessingConfiguration.contrast = value;
  41408. },
  41409. enumerable: true,
  41410. configurable: true
  41411. });
  41412. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41413. /**
  41414. * Gets the Color Grading 2D Lookup Texture.
  41415. */
  41416. get: function () {
  41417. return this._imageProcessingConfiguration.colorGradingTexture;
  41418. },
  41419. /**
  41420. * Sets the Color Grading 2D Lookup Texture.
  41421. */
  41422. set: function (value) {
  41423. this._imageProcessingConfiguration.colorGradingTexture = value;
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41429. /**
  41430. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41431. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41432. * 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;
  41433. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41434. */
  41435. get: function () {
  41436. return this._imageProcessingConfiguration.colorCurves;
  41437. },
  41438. /**
  41439. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41440. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41441. * 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;
  41442. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41443. */
  41444. set: function (value) {
  41445. this._imageProcessingConfiguration.colorCurves = value;
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. /**
  41451. * Returns the name of this material class.
  41452. */
  41453. PBRMaterial.prototype.getClassName = function () {
  41454. return "PBRMaterial";
  41455. };
  41456. /**
  41457. * Returns an array of the actively used textures.
  41458. * @returns - Array of BaseTextures
  41459. */
  41460. PBRMaterial.prototype.getActiveTextures = function () {
  41461. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41462. if (this._albedoTexture) {
  41463. activeTextures.push(this._albedoTexture);
  41464. }
  41465. if (this._ambientTexture) {
  41466. activeTextures.push(this._ambientTexture);
  41467. }
  41468. if (this._opacityTexture) {
  41469. activeTextures.push(this._opacityTexture);
  41470. }
  41471. if (this._reflectionTexture) {
  41472. activeTextures.push(this._reflectionTexture);
  41473. }
  41474. if (this._emissiveTexture) {
  41475. activeTextures.push(this._emissiveTexture);
  41476. }
  41477. if (this._reflectivityTexture) {
  41478. activeTextures.push(this._reflectivityTexture);
  41479. }
  41480. if (this._metallicTexture) {
  41481. activeTextures.push(this._metallicTexture);
  41482. }
  41483. if (this._microSurfaceTexture) {
  41484. activeTextures.push(this._microSurfaceTexture);
  41485. }
  41486. if (this._bumpTexture) {
  41487. activeTextures.push(this._bumpTexture);
  41488. }
  41489. if (this._lightmapTexture) {
  41490. activeTextures.push(this._lightmapTexture);
  41491. }
  41492. if (this._refractionTexture) {
  41493. activeTextures.push(this._refractionTexture);
  41494. }
  41495. return activeTextures;
  41496. };
  41497. /**
  41498. * Checks to see if a texture is used in the material.
  41499. * @param texture - Base texture to use.
  41500. * @returns - Boolean specifying if a texture is used in the material.
  41501. */
  41502. PBRMaterial.prototype.hasTexture = function (texture) {
  41503. if (_super.prototype.hasTexture.call(this, texture)) {
  41504. return true;
  41505. }
  41506. if (this._albedoTexture === texture) {
  41507. return true;
  41508. }
  41509. if (this._ambientTexture === texture) {
  41510. return true;
  41511. }
  41512. if (this._opacityTexture === texture) {
  41513. return true;
  41514. }
  41515. if (this._reflectionTexture === texture) {
  41516. return true;
  41517. }
  41518. if (this._reflectivityTexture === texture) {
  41519. return true;
  41520. }
  41521. if (this._metallicTexture === texture) {
  41522. return true;
  41523. }
  41524. if (this._microSurfaceTexture === texture) {
  41525. return true;
  41526. }
  41527. if (this._bumpTexture === texture) {
  41528. return true;
  41529. }
  41530. if (this._lightmapTexture === texture) {
  41531. return true;
  41532. }
  41533. if (this._refractionTexture === texture) {
  41534. return true;
  41535. }
  41536. return false;
  41537. };
  41538. /**
  41539. * Makes a duplicate of the current material.
  41540. * @param name - name to use for the new material.
  41541. */
  41542. PBRMaterial.prototype.clone = function (name) {
  41543. var _this = this;
  41544. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41545. clone.id = name;
  41546. clone.name = name;
  41547. return clone;
  41548. };
  41549. /**
  41550. * Serializes this PBR Material.
  41551. * @returns - An object with the serialized material.
  41552. */
  41553. PBRMaterial.prototype.serialize = function () {
  41554. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41555. serializationObject.customType = "BABYLON.PBRMaterial";
  41556. return serializationObject;
  41557. };
  41558. // Statics
  41559. /**
  41560. * Parses a PBR Material from a serialized object.
  41561. * @param source - Serialized object.
  41562. * @param scene - BJS scene instance.
  41563. * @param rootUrl - url for the scene object
  41564. * @returns - PBRMaterial
  41565. */
  41566. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41567. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41568. };
  41569. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41570. /**
  41571. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41572. */
  41573. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41574. /**
  41575. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41576. */
  41577. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41578. /**
  41579. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41580. * They are also discarded below the alpha cutoff threshold to improve performances.
  41581. */
  41582. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41583. __decorate([
  41584. BABYLON.serialize(),
  41585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41586. ], PBRMaterial.prototype, "directIntensity", void 0);
  41587. __decorate([
  41588. BABYLON.serialize(),
  41589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41590. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41591. __decorate([
  41592. BABYLON.serialize(),
  41593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41594. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41595. __decorate([
  41596. BABYLON.serialize(),
  41597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41598. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41599. __decorate([
  41600. BABYLON.serialize(),
  41601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41602. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41603. __decorate([
  41604. BABYLON.serializeAsTexture(),
  41605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41606. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41607. __decorate([
  41608. BABYLON.serializeAsTexture(),
  41609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41610. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41611. __decorate([
  41612. BABYLON.serialize(),
  41613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41614. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41615. __decorate([
  41616. BABYLON.serializeAsTexture(),
  41617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41618. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41619. __decorate([
  41620. BABYLON.serializeAsTexture(),
  41621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41622. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41623. __decorate([
  41624. BABYLON.serializeAsTexture(),
  41625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41626. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41627. __decorate([
  41628. BABYLON.serializeAsTexture(),
  41629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41630. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41631. __decorate([
  41632. BABYLON.serializeAsTexture(),
  41633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41634. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41635. __decorate([
  41636. BABYLON.serialize(),
  41637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41638. ], PBRMaterial.prototype, "metallic", void 0);
  41639. __decorate([
  41640. BABYLON.serialize(),
  41641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41642. ], PBRMaterial.prototype, "roughness", void 0);
  41643. __decorate([
  41644. BABYLON.serializeAsTexture(),
  41645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41646. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41647. __decorate([
  41648. BABYLON.serializeAsTexture(),
  41649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41650. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41651. __decorate([
  41652. BABYLON.serializeAsTexture(),
  41653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41654. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41655. __decorate([
  41656. BABYLON.serializeAsTexture(),
  41657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41658. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41659. __decorate([
  41660. BABYLON.serializeAsColor3("ambient"),
  41661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41662. ], PBRMaterial.prototype, "ambientColor", void 0);
  41663. __decorate([
  41664. BABYLON.serializeAsColor3("albedo"),
  41665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41666. ], PBRMaterial.prototype, "albedoColor", void 0);
  41667. __decorate([
  41668. BABYLON.serializeAsColor3("reflectivity"),
  41669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41670. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41671. __decorate([
  41672. BABYLON.serializeAsColor3("reflection"),
  41673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41674. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41675. __decorate([
  41676. BABYLON.serializeAsColor3("emissive"),
  41677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41678. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41679. __decorate([
  41680. BABYLON.serialize(),
  41681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41682. ], PBRMaterial.prototype, "microSurface", void 0);
  41683. __decorate([
  41684. BABYLON.serialize(),
  41685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41686. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41687. __decorate([
  41688. BABYLON.serialize(),
  41689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41690. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41691. __decorate([
  41692. BABYLON.serialize(),
  41693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41694. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41695. __decorate([
  41696. BABYLON.serialize(),
  41697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41698. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41699. __decorate([
  41700. BABYLON.serialize(),
  41701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41702. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41703. __decorate([
  41704. BABYLON.serialize(),
  41705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41706. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41707. __decorate([
  41708. BABYLON.serialize(),
  41709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41710. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41711. __decorate([
  41712. BABYLON.serialize(),
  41713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41714. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41715. __decorate([
  41716. BABYLON.serialize(),
  41717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41718. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41719. __decorate([
  41720. BABYLON.serialize(),
  41721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41722. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41723. __decorate([
  41724. BABYLON.serialize(),
  41725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41726. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41727. __decorate([
  41728. BABYLON.serialize(),
  41729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41730. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41731. __decorate([
  41732. BABYLON.serialize(),
  41733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41734. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41735. __decorate([
  41736. BABYLON.serialize(),
  41737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41738. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41739. __decorate([
  41740. BABYLON.serialize(),
  41741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41742. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41743. __decorate([
  41744. BABYLON.serialize(),
  41745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41746. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41747. __decorate([
  41748. BABYLON.serialize(),
  41749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41750. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41751. __decorate([
  41752. BABYLON.serialize(),
  41753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41754. ], PBRMaterial.prototype, "useParallax", void 0);
  41755. __decorate([
  41756. BABYLON.serialize(),
  41757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41758. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41759. __decorate([
  41760. BABYLON.serialize(),
  41761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41762. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41763. __decorate([
  41764. BABYLON.serialize(),
  41765. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41766. ], PBRMaterial.prototype, "disableLighting", void 0);
  41767. __decorate([
  41768. BABYLON.serialize(),
  41769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41770. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41771. __decorate([
  41772. BABYLON.serialize(),
  41773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41774. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41775. __decorate([
  41776. BABYLON.serialize(),
  41777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41778. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41779. __decorate([
  41780. BABYLON.serialize(),
  41781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41782. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41783. __decorate([
  41784. BABYLON.serialize(),
  41785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41786. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41787. __decorate([
  41788. BABYLON.serialize(),
  41789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41790. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41791. __decorate([
  41792. BABYLON.serialize(),
  41793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41794. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41795. __decorate([
  41796. BABYLON.serializeAsTexture(),
  41797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41798. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41799. __decorate([
  41800. BABYLON.serialize(),
  41801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41802. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41803. __decorate([
  41804. BABYLON.serialize(),
  41805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41806. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41807. __decorate([
  41808. BABYLON.serialize(),
  41809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41810. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41811. return PBRMaterial;
  41812. }(BABYLON.PBRBaseMaterial));
  41813. BABYLON.PBRMaterial = PBRMaterial;
  41814. })(BABYLON || (BABYLON = {}));
  41815. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41816. var BABYLON;
  41817. (function (BABYLON) {
  41818. /**
  41819. * The PBR material of BJS following the metal roughness convention.
  41820. *
  41821. * This fits to the PBR convention in the GLTF definition:
  41822. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41823. */
  41824. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41825. __extends(PBRMetallicRoughnessMaterial, _super);
  41826. /**
  41827. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41828. *
  41829. * @param name The material name
  41830. * @param scene The scene the material will be use in.
  41831. */
  41832. function PBRMetallicRoughnessMaterial(name, scene) {
  41833. var _this = _super.call(this, name, scene) || this;
  41834. _this._useRoughnessFromMetallicTextureAlpha = false;
  41835. _this._useRoughnessFromMetallicTextureGreen = true;
  41836. _this._useMetallnessFromMetallicTextureBlue = true;
  41837. _this._forceMetallicWorkflow = true;
  41838. return _this;
  41839. }
  41840. /**
  41841. * Return the currrent class name of the material.
  41842. */
  41843. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41844. return "PBRMetallicRoughnessMaterial";
  41845. };
  41846. /**
  41847. * Return the active textures of the material.
  41848. */
  41849. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41850. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41851. if (this.baseTexture) {
  41852. activeTextures.push(this.baseTexture);
  41853. }
  41854. if (this.metallicRoughnessTexture) {
  41855. activeTextures.push(this.metallicRoughnessTexture);
  41856. }
  41857. return activeTextures;
  41858. };
  41859. /**
  41860. * Checks to see if a texture is used in the material.
  41861. * @param texture - Base texture to use.
  41862. * @returns - Boolean specifying if a texture is used in the material.
  41863. */
  41864. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41865. if (_super.prototype.hasTexture.call(this, texture)) {
  41866. return true;
  41867. }
  41868. if (this.baseTexture === texture) {
  41869. return true;
  41870. }
  41871. if (this.metallicRoughnessTexture === texture) {
  41872. return true;
  41873. }
  41874. return false;
  41875. };
  41876. /**
  41877. * Makes a duplicate of the current material.
  41878. * @param name - name to use for the new material.
  41879. */
  41880. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41881. var _this = this;
  41882. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41883. clone.id = name;
  41884. clone.name = name;
  41885. return clone;
  41886. };
  41887. /**
  41888. * Serialize the material to a parsable JSON object.
  41889. */
  41890. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  41891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41892. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  41893. return serializationObject;
  41894. };
  41895. /**
  41896. * Parses a JSON object correponding to the serialize function.
  41897. */
  41898. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  41899. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  41900. };
  41901. __decorate([
  41902. BABYLON.serializeAsColor3(),
  41903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41904. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  41905. __decorate([
  41906. BABYLON.serializeAsTexture(),
  41907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41908. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  41909. __decorate([
  41910. BABYLON.serialize(),
  41911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41912. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  41913. __decorate([
  41914. BABYLON.serialize(),
  41915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41916. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  41917. __decorate([
  41918. BABYLON.serializeAsTexture(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  41920. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  41921. return PBRMetallicRoughnessMaterial;
  41922. }(BABYLON.PBRBaseSimpleMaterial));
  41923. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  41924. })(BABYLON || (BABYLON = {}));
  41925. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  41926. var BABYLON;
  41927. (function (BABYLON) {
  41928. /**
  41929. * The PBR material of BJS following the specular glossiness convention.
  41930. *
  41931. * This fits to the PBR convention in the GLTF definition:
  41932. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  41933. */
  41934. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  41935. __extends(PBRSpecularGlossinessMaterial, _super);
  41936. /**
  41937. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  41938. *
  41939. * @param name The material name
  41940. * @param scene The scene the material will be use in.
  41941. */
  41942. function PBRSpecularGlossinessMaterial(name, scene) {
  41943. var _this = _super.call(this, name, scene) || this;
  41944. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  41945. return _this;
  41946. }
  41947. /**
  41948. * Return the currrent class name of the material.
  41949. */
  41950. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  41951. return "PBRSpecularGlossinessMaterial";
  41952. };
  41953. /**
  41954. * Return the active textures of the material.
  41955. */
  41956. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  41957. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41958. if (this.diffuseTexture) {
  41959. activeTextures.push(this.diffuseTexture);
  41960. }
  41961. if (this.specularGlossinessTexture) {
  41962. activeTextures.push(this.specularGlossinessTexture);
  41963. }
  41964. return activeTextures;
  41965. };
  41966. /**
  41967. * Checks to see if a texture is used in the material.
  41968. * @param texture - Base texture to use.
  41969. * @returns - Boolean specifying if a texture is used in the material.
  41970. */
  41971. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  41972. if (_super.prototype.hasTexture.call(this, texture)) {
  41973. return true;
  41974. }
  41975. if (this.diffuseTexture === texture) {
  41976. return true;
  41977. }
  41978. if (this.specularGlossinessTexture === texture) {
  41979. return true;
  41980. }
  41981. return false;
  41982. };
  41983. /**
  41984. * Makes a duplicate of the current material.
  41985. * @param name - name to use for the new material.
  41986. */
  41987. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  41988. var _this = this;
  41989. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  41990. clone.id = name;
  41991. clone.name = name;
  41992. return clone;
  41993. };
  41994. /**
  41995. * Serialize the material to a parsable JSON object.
  41996. */
  41997. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  41998. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41999. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42000. return serializationObject;
  42001. };
  42002. /**
  42003. * Parses a JSON object correponding to the serialize function.
  42004. */
  42005. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42006. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42007. };
  42008. __decorate([
  42009. BABYLON.serializeAsColor3("diffuse"),
  42010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42011. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42012. __decorate([
  42013. BABYLON.serializeAsTexture(),
  42014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42015. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42016. __decorate([
  42017. BABYLON.serializeAsColor3("specular"),
  42018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42019. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42020. __decorate([
  42021. BABYLON.serialize(),
  42022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42023. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42024. __decorate([
  42025. BABYLON.serializeAsTexture(),
  42026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42027. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42028. return PBRSpecularGlossinessMaterial;
  42029. }(BABYLON.PBRBaseSimpleMaterial));
  42030. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42031. })(BABYLON || (BABYLON = {}));
  42032. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42033. var BABYLON;
  42034. (function (BABYLON) {
  42035. BABYLON.CameraInputTypes = {};
  42036. var CameraInputsManager = /** @class */ (function () {
  42037. function CameraInputsManager(camera) {
  42038. this.attached = {};
  42039. this.camera = camera;
  42040. this.checkInputs = function () { };
  42041. }
  42042. /**
  42043. * Add an input method to a camera.
  42044. * builtin inputs example: camera.inputs.addGamepad();
  42045. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42046. * @param input camera input method
  42047. */
  42048. CameraInputsManager.prototype.add = function (input) {
  42049. var type = input.getSimpleName();
  42050. if (this.attached[type]) {
  42051. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42052. return;
  42053. }
  42054. this.attached[type] = input;
  42055. input.camera = this.camera;
  42056. //for checkInputs, we are dynamically creating a function
  42057. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42058. if (input.checkInputs) {
  42059. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42060. }
  42061. if (this.attachedElement) {
  42062. input.attachControl(this.attachedElement);
  42063. }
  42064. };
  42065. /**
  42066. * Remove a specific input method from a camera
  42067. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42068. * @param inputToRemove camera input method
  42069. */
  42070. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42071. for (var cam in this.attached) {
  42072. var input = this.attached[cam];
  42073. if (input === inputToRemove) {
  42074. input.detachControl(this.attachedElement);
  42075. input.camera = null;
  42076. delete this.attached[cam];
  42077. this.rebuildInputCheck();
  42078. }
  42079. }
  42080. };
  42081. CameraInputsManager.prototype.removeByType = function (inputType) {
  42082. for (var cam in this.attached) {
  42083. var input = this.attached[cam];
  42084. if (input.getClassName() === inputType) {
  42085. input.detachControl(this.attachedElement);
  42086. input.camera = null;
  42087. delete this.attached[cam];
  42088. this.rebuildInputCheck();
  42089. }
  42090. }
  42091. };
  42092. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42093. var current = this.checkInputs;
  42094. return function () {
  42095. current();
  42096. fn();
  42097. };
  42098. };
  42099. CameraInputsManager.prototype.attachInput = function (input) {
  42100. if (this.attachedElement) {
  42101. input.attachControl(this.attachedElement, this.noPreventDefault);
  42102. }
  42103. };
  42104. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42105. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42106. if (this.attachedElement) {
  42107. return;
  42108. }
  42109. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42110. this.attachedElement = element;
  42111. this.noPreventDefault = noPreventDefault;
  42112. for (var cam in this.attached) {
  42113. this.attached[cam].attachControl(element, noPreventDefault);
  42114. }
  42115. };
  42116. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42117. if (disconnect === void 0) { disconnect = false; }
  42118. if (this.attachedElement !== element) {
  42119. return;
  42120. }
  42121. for (var cam in this.attached) {
  42122. this.attached[cam].detachControl(element);
  42123. if (disconnect) {
  42124. this.attached[cam].camera = null;
  42125. }
  42126. }
  42127. this.attachedElement = null;
  42128. };
  42129. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42130. this.checkInputs = function () { };
  42131. for (var cam in this.attached) {
  42132. var input = this.attached[cam];
  42133. if (input.checkInputs) {
  42134. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42135. }
  42136. }
  42137. };
  42138. /**
  42139. * Remove all attached input methods from a camera
  42140. */
  42141. CameraInputsManager.prototype.clear = function () {
  42142. if (this.attachedElement) {
  42143. this.detachElement(this.attachedElement, true);
  42144. }
  42145. this.attached = {};
  42146. this.attachedElement = null;
  42147. this.checkInputs = function () { };
  42148. };
  42149. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42150. var inputs = {};
  42151. for (var cam in this.attached) {
  42152. var input = this.attached[cam];
  42153. var res = BABYLON.SerializationHelper.Serialize(input);
  42154. inputs[input.getClassName()] = res;
  42155. }
  42156. serializedCamera.inputsmgr = inputs;
  42157. };
  42158. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42159. var parsedInputs = parsedCamera.inputsmgr;
  42160. if (parsedInputs) {
  42161. this.clear();
  42162. for (var n in parsedInputs) {
  42163. var construct = BABYLON.CameraInputTypes[n];
  42164. if (construct) {
  42165. var parsedinput = parsedInputs[n];
  42166. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42167. this.add(input);
  42168. }
  42169. }
  42170. }
  42171. else {
  42172. //2016-03-08 this part is for managing backward compatibility
  42173. for (var n in this.attached) {
  42174. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42175. if (construct) {
  42176. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42177. this.remove(this.attached[n]);
  42178. this.add(input);
  42179. }
  42180. }
  42181. }
  42182. };
  42183. return CameraInputsManager;
  42184. }());
  42185. BABYLON.CameraInputsManager = CameraInputsManager;
  42186. })(BABYLON || (BABYLON = {}));
  42187. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42188. var BABYLON;
  42189. (function (BABYLON) {
  42190. var TargetCamera = /** @class */ (function (_super) {
  42191. __extends(TargetCamera, _super);
  42192. function TargetCamera(name, position, scene) {
  42193. var _this = _super.call(this, name, position, scene) || this;
  42194. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42195. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42196. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42197. _this.speed = 2.0;
  42198. _this.noRotationConstraint = false;
  42199. _this.lockedTarget = null;
  42200. _this._currentTarget = BABYLON.Vector3.Zero();
  42201. _this._viewMatrix = BABYLON.Matrix.Zero();
  42202. _this._camMatrix = BABYLON.Matrix.Zero();
  42203. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42204. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42205. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42206. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42207. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42208. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42209. _this._tempMatrix = BABYLON.Matrix.Zero();
  42210. return _this;
  42211. }
  42212. TargetCamera.prototype.getFrontPosition = function (distance) {
  42213. this.getWorldMatrix();
  42214. var direction = this.getTarget().subtract(this.position);
  42215. direction.normalize();
  42216. direction.scaleInPlace(distance);
  42217. return this.globalPosition.add(direction);
  42218. };
  42219. TargetCamera.prototype._getLockedTargetPosition = function () {
  42220. if (!this.lockedTarget) {
  42221. return null;
  42222. }
  42223. if (this.lockedTarget.absolutePosition) {
  42224. this.lockedTarget.computeWorldMatrix();
  42225. }
  42226. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42227. };
  42228. TargetCamera.prototype.storeState = function () {
  42229. this._storedPosition = this.position.clone();
  42230. this._storedRotation = this.rotation.clone();
  42231. if (this.rotationQuaternion) {
  42232. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42233. }
  42234. return _super.prototype.storeState.call(this);
  42235. };
  42236. /**
  42237. * Restored camera state. You must call storeState() first
  42238. */
  42239. TargetCamera.prototype._restoreStateValues = function () {
  42240. if (!_super.prototype._restoreStateValues.call(this)) {
  42241. return false;
  42242. }
  42243. this.position = this._storedPosition.clone();
  42244. this.rotation = this._storedRotation.clone();
  42245. if (this.rotationQuaternion) {
  42246. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42247. }
  42248. this.cameraDirection.copyFromFloats(0, 0, 0);
  42249. this.cameraRotation.copyFromFloats(0, 0);
  42250. return true;
  42251. };
  42252. // Cache
  42253. TargetCamera.prototype._initCache = function () {
  42254. _super.prototype._initCache.call(this);
  42255. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42256. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42257. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42258. };
  42259. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42260. if (!ignoreParentClass) {
  42261. _super.prototype._updateCache.call(this);
  42262. }
  42263. var lockedTargetPosition = this._getLockedTargetPosition();
  42264. if (!lockedTargetPosition) {
  42265. this._cache.lockedTarget = null;
  42266. }
  42267. else {
  42268. if (!this._cache.lockedTarget) {
  42269. this._cache.lockedTarget = lockedTargetPosition.clone();
  42270. }
  42271. else {
  42272. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42273. }
  42274. }
  42275. this._cache.rotation.copyFrom(this.rotation);
  42276. if (this.rotationQuaternion)
  42277. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42278. };
  42279. // Synchronized
  42280. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42281. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42282. return false;
  42283. }
  42284. var lockedTargetPosition = this._getLockedTargetPosition();
  42285. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42286. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42287. };
  42288. // Methods
  42289. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42290. var engine = this.getEngine();
  42291. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42292. };
  42293. // Target
  42294. TargetCamera.prototype.setTarget = function (target) {
  42295. this.upVector.normalize();
  42296. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42297. this._camMatrix.invert();
  42298. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42299. var vDir = target.subtract(this.position);
  42300. if (vDir.x >= 0.0) {
  42301. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42302. }
  42303. else {
  42304. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42305. }
  42306. this.rotation.z = 0;
  42307. if (isNaN(this.rotation.x)) {
  42308. this.rotation.x = 0;
  42309. }
  42310. if (isNaN(this.rotation.y)) {
  42311. this.rotation.y = 0;
  42312. }
  42313. if (isNaN(this.rotation.z)) {
  42314. this.rotation.z = 0;
  42315. }
  42316. if (this.rotationQuaternion) {
  42317. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42318. }
  42319. };
  42320. /**
  42321. * Return the current target position of the camera. This value is expressed in local space.
  42322. */
  42323. TargetCamera.prototype.getTarget = function () {
  42324. return this._currentTarget;
  42325. };
  42326. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42327. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42328. };
  42329. TargetCamera.prototype._updatePosition = function () {
  42330. if (this.parent) {
  42331. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42332. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42333. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42334. return;
  42335. }
  42336. this.position.addInPlace(this.cameraDirection);
  42337. };
  42338. TargetCamera.prototype._checkInputs = function () {
  42339. var needToMove = this._decideIfNeedsToMove();
  42340. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42341. // Move
  42342. if (needToMove) {
  42343. this._updatePosition();
  42344. }
  42345. // Rotate
  42346. if (needToRotate) {
  42347. this.rotation.x += this.cameraRotation.x;
  42348. this.rotation.y += this.cameraRotation.y;
  42349. //rotate, if quaternion is set and rotation was used
  42350. if (this.rotationQuaternion) {
  42351. var len = this.rotation.lengthSquared();
  42352. if (len) {
  42353. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42354. }
  42355. }
  42356. if (!this.noRotationConstraint) {
  42357. var limit = (Math.PI / 2) * 0.95;
  42358. if (this.rotation.x > limit)
  42359. this.rotation.x = limit;
  42360. if (this.rotation.x < -limit)
  42361. this.rotation.x = -limit;
  42362. }
  42363. }
  42364. // Inertia
  42365. if (needToMove) {
  42366. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42367. this.cameraDirection.x = 0;
  42368. }
  42369. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42370. this.cameraDirection.y = 0;
  42371. }
  42372. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42373. this.cameraDirection.z = 0;
  42374. }
  42375. this.cameraDirection.scaleInPlace(this.inertia);
  42376. }
  42377. if (needToRotate) {
  42378. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42379. this.cameraRotation.x = 0;
  42380. }
  42381. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42382. this.cameraRotation.y = 0;
  42383. }
  42384. this.cameraRotation.scaleInPlace(this.inertia);
  42385. }
  42386. _super.prototype._checkInputs.call(this);
  42387. };
  42388. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42389. if (this.rotationQuaternion) {
  42390. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42391. }
  42392. else {
  42393. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42394. }
  42395. //update the up vector!
  42396. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42397. };
  42398. TargetCamera.prototype._getViewMatrix = function () {
  42399. if (this.lockedTarget) {
  42400. this.setTarget(this._getLockedTargetPosition());
  42401. }
  42402. // Compute
  42403. this._updateCameraRotationMatrix();
  42404. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42405. // Computing target and final matrix
  42406. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42407. if (this.getScene().useRightHandedSystem) {
  42408. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42409. }
  42410. else {
  42411. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42412. }
  42413. return this._viewMatrix;
  42414. };
  42415. /**
  42416. * @override
  42417. * Override Camera.createRigCamera
  42418. */
  42419. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42420. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42421. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42422. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42423. if (!this.rotationQuaternion) {
  42424. this.rotationQuaternion = new BABYLON.Quaternion();
  42425. }
  42426. rigCamera._cameraRigParams = {};
  42427. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42428. }
  42429. return rigCamera;
  42430. }
  42431. return null;
  42432. };
  42433. /**
  42434. * @override
  42435. * Override Camera._updateRigCameras
  42436. */
  42437. TargetCamera.prototype._updateRigCameras = function () {
  42438. var camLeft = this._rigCameras[0];
  42439. var camRight = this._rigCameras[1];
  42440. switch (this.cameraRigMode) {
  42441. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42442. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42443. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42444. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42445. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42446. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42447. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42448. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42449. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42450. camLeft.setTarget(this.getTarget());
  42451. camRight.setTarget(this.getTarget());
  42452. break;
  42453. case BABYLON.Camera.RIG_MODE_VR:
  42454. if (camLeft.rotationQuaternion) {
  42455. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42456. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42457. }
  42458. else {
  42459. camLeft.rotation.copyFrom(this.rotation);
  42460. camRight.rotation.copyFrom(this.rotation);
  42461. }
  42462. camLeft.position.copyFrom(this.position);
  42463. camRight.position.copyFrom(this.position);
  42464. break;
  42465. }
  42466. _super.prototype._updateRigCameras.call(this);
  42467. };
  42468. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42469. if (!this._rigCamTransformMatrix) {
  42470. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42471. }
  42472. var target = this.getTarget();
  42473. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42474. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42475. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42476. };
  42477. TargetCamera.prototype.getClassName = function () {
  42478. return "TargetCamera";
  42479. };
  42480. __decorate([
  42481. BABYLON.serializeAsVector3()
  42482. ], TargetCamera.prototype, "rotation", void 0);
  42483. __decorate([
  42484. BABYLON.serialize()
  42485. ], TargetCamera.prototype, "speed", void 0);
  42486. __decorate([
  42487. BABYLON.serializeAsMeshReference("lockedTargetId")
  42488. ], TargetCamera.prototype, "lockedTarget", void 0);
  42489. return TargetCamera;
  42490. }(BABYLON.Camera));
  42491. BABYLON.TargetCamera = TargetCamera;
  42492. })(BABYLON || (BABYLON = {}));
  42493. //# sourceMappingURL=babylon.targetCamera.js.map
  42494. var BABYLON;
  42495. (function (BABYLON) {
  42496. var FreeCameraMouseInput = /** @class */ (function () {
  42497. function FreeCameraMouseInput(touchEnabled) {
  42498. if (touchEnabled === void 0) { touchEnabled = true; }
  42499. this.touchEnabled = touchEnabled;
  42500. this.buttons = [0, 1, 2];
  42501. this.angularSensibility = 2000.0;
  42502. this.previousPosition = null;
  42503. }
  42504. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42505. var _this = this;
  42506. var engine = this.camera.getEngine();
  42507. if (!this._pointerInput) {
  42508. this._pointerInput = function (p, s) {
  42509. var evt = p.event;
  42510. if (engine.isInVRExclusivePointerMode) {
  42511. return;
  42512. }
  42513. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42514. return;
  42515. }
  42516. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42517. return;
  42518. }
  42519. var srcElement = (evt.srcElement || evt.target);
  42520. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42521. try {
  42522. srcElement.setPointerCapture(evt.pointerId);
  42523. }
  42524. catch (e) {
  42525. //Nothing to do with the error. Execution will continue.
  42526. }
  42527. _this.previousPosition = {
  42528. x: evt.clientX,
  42529. y: evt.clientY
  42530. };
  42531. if (!noPreventDefault) {
  42532. evt.preventDefault();
  42533. element.focus();
  42534. }
  42535. }
  42536. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42537. try {
  42538. srcElement.releasePointerCapture(evt.pointerId);
  42539. }
  42540. catch (e) {
  42541. //Nothing to do with the error.
  42542. }
  42543. _this.previousPosition = null;
  42544. if (!noPreventDefault) {
  42545. evt.preventDefault();
  42546. }
  42547. }
  42548. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42549. if (!_this.previousPosition || engine.isPointerLock) {
  42550. return;
  42551. }
  42552. var offsetX = evt.clientX - _this.previousPosition.x;
  42553. var offsetY = evt.clientY - _this.previousPosition.y;
  42554. if (_this.camera.getScene().useRightHandedSystem) {
  42555. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42556. }
  42557. else {
  42558. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42559. }
  42560. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42561. _this.previousPosition = {
  42562. x: evt.clientX,
  42563. y: evt.clientY
  42564. };
  42565. if (!noPreventDefault) {
  42566. evt.preventDefault();
  42567. }
  42568. }
  42569. };
  42570. }
  42571. this._onMouseMove = function (evt) {
  42572. if (!engine.isPointerLock) {
  42573. return;
  42574. }
  42575. if (engine.isInVRExclusivePointerMode) {
  42576. return;
  42577. }
  42578. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42579. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42580. if (_this.camera.getScene().useRightHandedSystem) {
  42581. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42582. }
  42583. else {
  42584. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42585. }
  42586. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42587. _this.previousPosition = null;
  42588. if (!noPreventDefault) {
  42589. evt.preventDefault();
  42590. }
  42591. };
  42592. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42593. element.addEventListener("mousemove", this._onMouseMove, false);
  42594. };
  42595. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42596. if (this._observer && element) {
  42597. this.camera.getScene().onPointerObservable.remove(this._observer);
  42598. if (this._onMouseMove) {
  42599. element.removeEventListener("mousemove", this._onMouseMove);
  42600. }
  42601. this._observer = null;
  42602. this._onMouseMove = null;
  42603. this.previousPosition = null;
  42604. }
  42605. };
  42606. FreeCameraMouseInput.prototype.getClassName = function () {
  42607. return "FreeCameraMouseInput";
  42608. };
  42609. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42610. return "mouse";
  42611. };
  42612. __decorate([
  42613. BABYLON.serialize()
  42614. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42615. __decorate([
  42616. BABYLON.serialize()
  42617. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42618. return FreeCameraMouseInput;
  42619. }());
  42620. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42621. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42622. })(BABYLON || (BABYLON = {}));
  42623. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42624. var BABYLON;
  42625. (function (BABYLON) {
  42626. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42627. function FreeCameraKeyboardMoveInput() {
  42628. this._keys = new Array();
  42629. this.keysUp = [38];
  42630. this.keysDown = [40];
  42631. this.keysLeft = [37];
  42632. this.keysRight = [39];
  42633. }
  42634. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42635. var _this = this;
  42636. if (this._onCanvasBlurObserver) {
  42637. return;
  42638. }
  42639. this._scene = this.camera.getScene();
  42640. this._engine = this._scene.getEngine();
  42641. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42642. _this._keys = [];
  42643. });
  42644. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42645. var evt = info.event;
  42646. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42647. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42648. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42649. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42650. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42651. var index = _this._keys.indexOf(evt.keyCode);
  42652. if (index === -1) {
  42653. _this._keys.push(evt.keyCode);
  42654. }
  42655. if (!noPreventDefault) {
  42656. evt.preventDefault();
  42657. }
  42658. }
  42659. }
  42660. else {
  42661. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42662. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42663. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42664. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42665. var index = _this._keys.indexOf(evt.keyCode);
  42666. if (index >= 0) {
  42667. _this._keys.splice(index, 1);
  42668. }
  42669. if (!noPreventDefault) {
  42670. evt.preventDefault();
  42671. }
  42672. }
  42673. }
  42674. });
  42675. };
  42676. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42677. if (this._scene) {
  42678. if (this._onKeyboardObserver) {
  42679. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42680. }
  42681. if (this._onCanvasBlurObserver) {
  42682. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42683. }
  42684. this._onKeyboardObserver = null;
  42685. this._onCanvasBlurObserver = null;
  42686. }
  42687. this._keys = [];
  42688. };
  42689. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42690. if (this._onKeyboardObserver) {
  42691. var camera = this.camera;
  42692. // Keyboard
  42693. for (var index = 0; index < this._keys.length; index++) {
  42694. var keyCode = this._keys[index];
  42695. var speed = camera._computeLocalCameraSpeed();
  42696. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42697. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42698. }
  42699. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42700. camera._localDirection.copyFromFloats(0, 0, speed);
  42701. }
  42702. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42703. camera._localDirection.copyFromFloats(speed, 0, 0);
  42704. }
  42705. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42706. camera._localDirection.copyFromFloats(0, 0, -speed);
  42707. }
  42708. if (camera.getScene().useRightHandedSystem) {
  42709. camera._localDirection.z *= -1;
  42710. }
  42711. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42712. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42713. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42714. }
  42715. }
  42716. };
  42717. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42718. return "FreeCameraKeyboardMoveInput";
  42719. };
  42720. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42721. this._keys = [];
  42722. };
  42723. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42724. return "keyboard";
  42725. };
  42726. __decorate([
  42727. BABYLON.serialize()
  42728. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42729. __decorate([
  42730. BABYLON.serialize()
  42731. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42732. __decorate([
  42733. BABYLON.serialize()
  42734. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42735. __decorate([
  42736. BABYLON.serialize()
  42737. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42738. return FreeCameraKeyboardMoveInput;
  42739. }());
  42740. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42741. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42742. })(BABYLON || (BABYLON = {}));
  42743. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42744. var BABYLON;
  42745. (function (BABYLON) {
  42746. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42747. __extends(FreeCameraInputsManager, _super);
  42748. function FreeCameraInputsManager(camera) {
  42749. return _super.call(this, camera) || this;
  42750. }
  42751. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42752. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42753. return this;
  42754. };
  42755. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42756. if (touchEnabled === void 0) { touchEnabled = true; }
  42757. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42758. return this;
  42759. };
  42760. FreeCameraInputsManager.prototype.addGamepad = function () {
  42761. this.add(new BABYLON.FreeCameraGamepadInput());
  42762. return this;
  42763. };
  42764. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42765. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42766. return this;
  42767. };
  42768. FreeCameraInputsManager.prototype.addTouch = function () {
  42769. this.add(new BABYLON.FreeCameraTouchInput());
  42770. return this;
  42771. };
  42772. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42773. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42774. return this;
  42775. };
  42776. return FreeCameraInputsManager;
  42777. }(BABYLON.CameraInputsManager));
  42778. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42779. })(BABYLON || (BABYLON = {}));
  42780. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42781. var BABYLON;
  42782. (function (BABYLON) {
  42783. var FreeCamera = /** @class */ (function (_super) {
  42784. __extends(FreeCamera, _super);
  42785. function FreeCamera(name, position, scene) {
  42786. var _this = _super.call(this, name, position, scene) || this;
  42787. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42788. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42789. _this.checkCollisions = false;
  42790. _this.applyGravity = false;
  42791. _this._needMoveForGravity = false;
  42792. _this._oldPosition = BABYLON.Vector3.Zero();
  42793. _this._diffPosition = BABYLON.Vector3.Zero();
  42794. _this._newPosition = BABYLON.Vector3.Zero();
  42795. // Collisions
  42796. _this._collisionMask = -1;
  42797. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42798. if (collidedMesh === void 0) { collidedMesh = null; }
  42799. //TODO move this to the collision coordinator!
  42800. if (_this.getScene().workerCollisions)
  42801. newPosition.multiplyInPlace(_this._collider._radius);
  42802. var updatePosition = function (newPos) {
  42803. _this._newPosition.copyFrom(newPos);
  42804. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42805. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42806. _this.position.addInPlace(_this._diffPosition);
  42807. if (_this.onCollide && collidedMesh) {
  42808. _this.onCollide(collidedMesh);
  42809. }
  42810. }
  42811. };
  42812. updatePosition(newPosition);
  42813. };
  42814. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42815. _this.inputs.addKeyboard().addMouse();
  42816. return _this;
  42817. }
  42818. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42819. //-- begin properties for backward compatibility for inputs
  42820. /**
  42821. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42822. * Higher values reduce sensitivity.
  42823. */
  42824. get: function () {
  42825. var mouse = this.inputs.attached["mouse"];
  42826. if (mouse)
  42827. return mouse.angularSensibility;
  42828. return 0;
  42829. },
  42830. /**
  42831. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42832. * Higher values reduce sensitivity.
  42833. */
  42834. set: function (value) {
  42835. var mouse = this.inputs.attached["mouse"];
  42836. if (mouse)
  42837. mouse.angularSensibility = value;
  42838. },
  42839. enumerable: true,
  42840. configurable: true
  42841. });
  42842. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42843. get: function () {
  42844. var keyboard = this.inputs.attached["keyboard"];
  42845. if (keyboard)
  42846. return keyboard.keysUp;
  42847. return [];
  42848. },
  42849. set: function (value) {
  42850. var keyboard = this.inputs.attached["keyboard"];
  42851. if (keyboard)
  42852. keyboard.keysUp = value;
  42853. },
  42854. enumerable: true,
  42855. configurable: true
  42856. });
  42857. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42858. get: function () {
  42859. var keyboard = this.inputs.attached["keyboard"];
  42860. if (keyboard)
  42861. return keyboard.keysDown;
  42862. return [];
  42863. },
  42864. set: function (value) {
  42865. var keyboard = this.inputs.attached["keyboard"];
  42866. if (keyboard)
  42867. keyboard.keysDown = value;
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42873. get: function () {
  42874. var keyboard = this.inputs.attached["keyboard"];
  42875. if (keyboard)
  42876. return keyboard.keysLeft;
  42877. return [];
  42878. },
  42879. set: function (value) {
  42880. var keyboard = this.inputs.attached["keyboard"];
  42881. if (keyboard)
  42882. keyboard.keysLeft = value;
  42883. },
  42884. enumerable: true,
  42885. configurable: true
  42886. });
  42887. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42888. get: function () {
  42889. var keyboard = this.inputs.attached["keyboard"];
  42890. if (keyboard)
  42891. return keyboard.keysRight;
  42892. return [];
  42893. },
  42894. set: function (value) {
  42895. var keyboard = this.inputs.attached["keyboard"];
  42896. if (keyboard)
  42897. keyboard.keysRight = value;
  42898. },
  42899. enumerable: true,
  42900. configurable: true
  42901. });
  42902. // Controls
  42903. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42904. this.inputs.attachElement(element, noPreventDefault);
  42905. };
  42906. FreeCamera.prototype.detachControl = function (element) {
  42907. this.inputs.detachElement(element);
  42908. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42909. this.cameraRotation = new BABYLON.Vector2(0, 0);
  42910. };
  42911. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  42912. get: function () {
  42913. return this._collisionMask;
  42914. },
  42915. set: function (mask) {
  42916. this._collisionMask = !isNaN(mask) ? mask : -1;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. FreeCamera.prototype._collideWithWorld = function (displacement) {
  42922. var globalPosition;
  42923. if (this.parent) {
  42924. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  42925. }
  42926. else {
  42927. globalPosition = this.position;
  42928. }
  42929. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  42930. this._oldPosition.addInPlace(this.ellipsoidOffset);
  42931. if (!this._collider) {
  42932. this._collider = new BABYLON.Collider();
  42933. }
  42934. this._collider._radius = this.ellipsoid;
  42935. this._collider.collisionMask = this._collisionMask;
  42936. //no need for clone, as long as gravity is not on.
  42937. var actualDisplacement = displacement;
  42938. //add gravity to the direction to prevent the dual-collision checking
  42939. if (this.applyGravity) {
  42940. //this prevents mending with cameraDirection, a global variable of the free camera class.
  42941. actualDisplacement = displacement.add(this.getScene().gravity);
  42942. }
  42943. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42944. };
  42945. FreeCamera.prototype._checkInputs = function () {
  42946. if (!this._localDirection) {
  42947. this._localDirection = BABYLON.Vector3.Zero();
  42948. this._transformedDirection = BABYLON.Vector3.Zero();
  42949. }
  42950. this.inputs.checkInputs();
  42951. _super.prototype._checkInputs.call(this);
  42952. };
  42953. FreeCamera.prototype._decideIfNeedsToMove = function () {
  42954. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42955. };
  42956. FreeCamera.prototype._updatePosition = function () {
  42957. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  42958. this._collideWithWorld(this.cameraDirection);
  42959. }
  42960. else {
  42961. _super.prototype._updatePosition.call(this);
  42962. }
  42963. };
  42964. FreeCamera.prototype.dispose = function () {
  42965. this.inputs.clear();
  42966. _super.prototype.dispose.call(this);
  42967. };
  42968. FreeCamera.prototype.getClassName = function () {
  42969. return "FreeCamera";
  42970. };
  42971. __decorate([
  42972. BABYLON.serializeAsVector3()
  42973. ], FreeCamera.prototype, "ellipsoid", void 0);
  42974. __decorate([
  42975. BABYLON.serializeAsVector3()
  42976. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  42977. __decorate([
  42978. BABYLON.serialize()
  42979. ], FreeCamera.prototype, "checkCollisions", void 0);
  42980. __decorate([
  42981. BABYLON.serialize()
  42982. ], FreeCamera.prototype, "applyGravity", void 0);
  42983. return FreeCamera;
  42984. }(BABYLON.TargetCamera));
  42985. BABYLON.FreeCamera = FreeCamera;
  42986. })(BABYLON || (BABYLON = {}));
  42987. //# sourceMappingURL=babylon.freeCamera.js.map
  42988. var BABYLON;
  42989. (function (BABYLON) {
  42990. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  42991. function ArcRotateCameraKeyboardMoveInput() {
  42992. this._keys = new Array();
  42993. this.keysUp = [38];
  42994. this.keysDown = [40];
  42995. this.keysLeft = [37];
  42996. this.keysRight = [39];
  42997. this.keysReset = [220];
  42998. this.panningSensibility = 50.0;
  42999. this.zoomingSensibility = 25.0;
  43000. this.useAltToZoom = true;
  43001. }
  43002. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43003. var _this = this;
  43004. if (this._onCanvasBlurObserver) {
  43005. return;
  43006. }
  43007. this._scene = this.camera.getScene();
  43008. this._engine = this._scene.getEngine();
  43009. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43010. _this._keys = [];
  43011. });
  43012. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43013. var evt = info.event;
  43014. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43015. _this._ctrlPressed = evt.ctrlKey;
  43016. _this._altPressed = evt.altKey;
  43017. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43018. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43019. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43020. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43021. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43022. var index = _this._keys.indexOf(evt.keyCode);
  43023. if (index === -1) {
  43024. _this._keys.push(evt.keyCode);
  43025. }
  43026. if (evt.preventDefault) {
  43027. if (!noPreventDefault) {
  43028. evt.preventDefault();
  43029. }
  43030. }
  43031. }
  43032. }
  43033. else {
  43034. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43035. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43036. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43037. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43038. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43039. var index = _this._keys.indexOf(evt.keyCode);
  43040. if (index >= 0) {
  43041. _this._keys.splice(index, 1);
  43042. }
  43043. if (evt.preventDefault) {
  43044. if (!noPreventDefault) {
  43045. evt.preventDefault();
  43046. }
  43047. }
  43048. }
  43049. }
  43050. });
  43051. };
  43052. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43053. if (this._scene) {
  43054. if (this._onKeyboardObserver) {
  43055. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43056. }
  43057. if (this._onCanvasBlurObserver) {
  43058. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43059. }
  43060. this._onKeyboardObserver = null;
  43061. this._onCanvasBlurObserver = null;
  43062. }
  43063. this._keys = [];
  43064. };
  43065. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43066. if (this._onKeyboardObserver) {
  43067. var camera = this.camera;
  43068. for (var index = 0; index < this._keys.length; index++) {
  43069. var keyCode = this._keys[index];
  43070. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43071. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43072. camera.inertialPanningX -= 1 / this.panningSensibility;
  43073. }
  43074. else {
  43075. camera.inertialAlphaOffset -= 0.01;
  43076. }
  43077. }
  43078. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43079. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43080. camera.inertialPanningY += 1 / this.panningSensibility;
  43081. }
  43082. else if (this._altPressed && this.useAltToZoom) {
  43083. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43084. }
  43085. else {
  43086. camera.inertialBetaOffset -= 0.01;
  43087. }
  43088. }
  43089. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43090. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43091. camera.inertialPanningX += 1 / this.panningSensibility;
  43092. }
  43093. else {
  43094. camera.inertialAlphaOffset += 0.01;
  43095. }
  43096. }
  43097. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43098. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43099. camera.inertialPanningY -= 1 / this.panningSensibility;
  43100. }
  43101. else if (this._altPressed && this.useAltToZoom) {
  43102. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43103. }
  43104. else {
  43105. camera.inertialBetaOffset += 0.01;
  43106. }
  43107. }
  43108. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43109. camera.restoreState();
  43110. }
  43111. }
  43112. }
  43113. };
  43114. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43115. return "ArcRotateCameraKeyboardMoveInput";
  43116. };
  43117. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43118. return "keyboard";
  43119. };
  43120. __decorate([
  43121. BABYLON.serialize()
  43122. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43123. __decorate([
  43124. BABYLON.serialize()
  43125. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43126. __decorate([
  43127. BABYLON.serialize()
  43128. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43129. __decorate([
  43130. BABYLON.serialize()
  43131. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43132. __decorate([
  43133. BABYLON.serialize()
  43134. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43135. __decorate([
  43136. BABYLON.serialize()
  43137. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43138. __decorate([
  43139. BABYLON.serialize()
  43140. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43141. __decorate([
  43142. BABYLON.serialize()
  43143. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43144. return ArcRotateCameraKeyboardMoveInput;
  43145. }());
  43146. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43147. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43148. })(BABYLON || (BABYLON = {}));
  43149. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43150. var BABYLON;
  43151. (function (BABYLON) {
  43152. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43153. function ArcRotateCameraMouseWheelInput() {
  43154. this.wheelPrecision = 3.0;
  43155. /**
  43156. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43157. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43158. */
  43159. this.wheelDeltaPercentage = 0;
  43160. }
  43161. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43162. var _this = this;
  43163. this._wheel = function (p, s) {
  43164. //sanity check - this should be a PointerWheel event.
  43165. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43166. return;
  43167. var event = p.event;
  43168. var delta = 0;
  43169. if (event.wheelDelta) {
  43170. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43171. }
  43172. else if (event.detail) {
  43173. delta = -event.detail / _this.wheelPrecision;
  43174. }
  43175. if (delta)
  43176. _this.camera.inertialRadiusOffset += delta;
  43177. if (event.preventDefault) {
  43178. if (!noPreventDefault) {
  43179. event.preventDefault();
  43180. }
  43181. }
  43182. };
  43183. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43184. };
  43185. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43186. if (this._observer && element) {
  43187. this.camera.getScene().onPointerObservable.remove(this._observer);
  43188. this._observer = null;
  43189. this._wheel = null;
  43190. }
  43191. };
  43192. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43193. return "ArcRotateCameraMouseWheelInput";
  43194. };
  43195. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43196. return "mousewheel";
  43197. };
  43198. __decorate([
  43199. BABYLON.serialize()
  43200. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43201. __decorate([
  43202. BABYLON.serialize()
  43203. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43204. return ArcRotateCameraMouseWheelInput;
  43205. }());
  43206. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43207. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43208. })(BABYLON || (BABYLON = {}));
  43209. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43210. var BABYLON;
  43211. (function (BABYLON) {
  43212. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43213. function ArcRotateCameraPointersInput() {
  43214. this.buttons = [0, 1, 2];
  43215. this.angularSensibilityX = 1000.0;
  43216. this.angularSensibilityY = 1000.0;
  43217. this.pinchPrecision = 12.0;
  43218. /**
  43219. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43220. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43221. */
  43222. this.pinchDeltaPercentage = 0;
  43223. this.panningSensibility = 1000.0;
  43224. this.multiTouchPanning = true;
  43225. this.multiTouchPanAndZoom = true;
  43226. this._isPanClick = false;
  43227. this.pinchInwards = true;
  43228. }
  43229. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43230. var _this = this;
  43231. var engine = this.camera.getEngine();
  43232. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43233. var pointA = null;
  43234. var pointB = null;
  43235. var previousPinchSquaredDistance = 0;
  43236. var initialDistance = 0;
  43237. var twoFingerActivityCount = 0;
  43238. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43239. this._pointerInput = function (p, s) {
  43240. var evt = p.event;
  43241. var isTouch = p.event.pointerType === "touch";
  43242. if (engine.isInVRExclusivePointerMode) {
  43243. return;
  43244. }
  43245. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43246. return;
  43247. }
  43248. var srcElement = (evt.srcElement || evt.target);
  43249. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43250. try {
  43251. srcElement.setPointerCapture(evt.pointerId);
  43252. }
  43253. catch (e) {
  43254. //Nothing to do with the error. Execution will continue.
  43255. }
  43256. // Manage panning with pan button click
  43257. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43258. // manage pointers
  43259. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43260. if (pointA === null) {
  43261. pointA = cacheSoloPointer;
  43262. }
  43263. else if (pointB === null) {
  43264. pointB = cacheSoloPointer;
  43265. }
  43266. if (!noPreventDefault) {
  43267. evt.preventDefault();
  43268. element.focus();
  43269. }
  43270. }
  43271. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43272. _this.camera.restoreState();
  43273. }
  43274. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43275. try {
  43276. srcElement.releasePointerCapture(evt.pointerId);
  43277. }
  43278. catch (e) {
  43279. //Nothing to do with the error.
  43280. }
  43281. cacheSoloPointer = null;
  43282. previousPinchSquaredDistance = 0;
  43283. previousMultiTouchPanPosition.isPaning = false;
  43284. previousMultiTouchPanPosition.isPinching = false;
  43285. twoFingerActivityCount = 0;
  43286. initialDistance = 0;
  43287. if (!isTouch) {
  43288. pointB = null; // Mouse and pen are mono pointer
  43289. }
  43290. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43291. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43292. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43293. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43294. if (engine.badOS) {
  43295. pointA = pointB = null;
  43296. }
  43297. else {
  43298. //only remove the impacted pointer in case of multitouch allowing on most
  43299. //platforms switching from rotate to zoom and pan seamlessly.
  43300. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43301. pointA = pointB;
  43302. pointB = null;
  43303. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43304. }
  43305. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43306. pointB = null;
  43307. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43308. }
  43309. else {
  43310. pointA = pointB = null;
  43311. }
  43312. }
  43313. if (!noPreventDefault) {
  43314. evt.preventDefault();
  43315. }
  43316. }
  43317. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43318. if (!noPreventDefault) {
  43319. evt.preventDefault();
  43320. }
  43321. // One button down
  43322. if (pointA && pointB === null && cacheSoloPointer) {
  43323. if (_this.panningSensibility !== 0 &&
  43324. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43325. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43326. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43327. }
  43328. else {
  43329. var offsetX = evt.clientX - cacheSoloPointer.x;
  43330. var offsetY = evt.clientY - cacheSoloPointer.y;
  43331. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43332. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43333. }
  43334. cacheSoloPointer.x = evt.clientX;
  43335. cacheSoloPointer.y = evt.clientY;
  43336. }
  43337. else if (pointA && pointB) {
  43338. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43339. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43340. ed.x = evt.clientX;
  43341. ed.y = evt.clientY;
  43342. var direction = _this.pinchInwards ? 1 : -1;
  43343. var distX = pointA.x - pointB.x;
  43344. var distY = pointA.y - pointB.y;
  43345. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43346. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43347. if (previousPinchSquaredDistance === 0) {
  43348. initialDistance = pinchDistance;
  43349. previousPinchSquaredDistance = pinchSquaredDistance;
  43350. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43351. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43352. return;
  43353. }
  43354. if (_this.multiTouchPanAndZoom) {
  43355. if (_this.pinchDeltaPercentage) {
  43356. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43357. }
  43358. else {
  43359. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43360. (_this.pinchPrecision *
  43361. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43362. direction);
  43363. }
  43364. if (_this.panningSensibility !== 0) {
  43365. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43366. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43367. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43368. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43369. previousMultiTouchPanPosition.x = pointersCenterX;
  43370. previousMultiTouchPanPosition.y = pointersCenterY;
  43371. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43372. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43373. }
  43374. }
  43375. else {
  43376. twoFingerActivityCount++;
  43377. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43378. if (_this.pinchDeltaPercentage) {
  43379. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43380. }
  43381. else {
  43382. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43383. (_this.pinchPrecision *
  43384. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43385. direction);
  43386. }
  43387. previousMultiTouchPanPosition.isPaning = false;
  43388. previousMultiTouchPanPosition.isPinching = true;
  43389. }
  43390. else {
  43391. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43392. if (!previousMultiTouchPanPosition.isPaning) {
  43393. previousMultiTouchPanPosition.isPaning = true;
  43394. previousMultiTouchPanPosition.isPinching = false;
  43395. previousMultiTouchPanPosition.x = ed.x;
  43396. previousMultiTouchPanPosition.y = ed.y;
  43397. return;
  43398. }
  43399. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43400. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43401. }
  43402. }
  43403. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43404. previousMultiTouchPanPosition.x = ed.x;
  43405. previousMultiTouchPanPosition.y = ed.y;
  43406. }
  43407. }
  43408. previousPinchSquaredDistance = pinchSquaredDistance;
  43409. }
  43410. }
  43411. };
  43412. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43413. this._onContextMenu = function (evt) {
  43414. evt.preventDefault();
  43415. };
  43416. if (!this.camera._useCtrlForPanning) {
  43417. element.addEventListener("contextmenu", this._onContextMenu, false);
  43418. }
  43419. this._onLostFocus = function () {
  43420. //this._keys = [];
  43421. pointA = pointB = null;
  43422. previousPinchSquaredDistance = 0;
  43423. previousMultiTouchPanPosition.isPaning = false;
  43424. previousMultiTouchPanPosition.isPinching = false;
  43425. twoFingerActivityCount = 0;
  43426. cacheSoloPointer = null;
  43427. initialDistance = 0;
  43428. };
  43429. this._onMouseMove = function (evt) {
  43430. if (!engine.isPointerLock) {
  43431. return;
  43432. }
  43433. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43434. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43435. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43436. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43437. if (!noPreventDefault) {
  43438. evt.preventDefault();
  43439. }
  43440. };
  43441. this._onGestureStart = function (e) {
  43442. if (window.MSGesture === undefined) {
  43443. return;
  43444. }
  43445. if (!_this._MSGestureHandler) {
  43446. _this._MSGestureHandler = new MSGesture();
  43447. _this._MSGestureHandler.target = element;
  43448. }
  43449. _this._MSGestureHandler.addPointer(e.pointerId);
  43450. };
  43451. this._onGesture = function (e) {
  43452. _this.camera.radius *= e.scale;
  43453. if (e.preventDefault) {
  43454. if (!noPreventDefault) {
  43455. e.stopPropagation();
  43456. e.preventDefault();
  43457. }
  43458. }
  43459. };
  43460. element.addEventListener("mousemove", this._onMouseMove, false);
  43461. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43462. element.addEventListener("MSGestureChange", this._onGesture, false);
  43463. BABYLON.Tools.RegisterTopRootEvents([
  43464. { name: "blur", handler: this._onLostFocus }
  43465. ]);
  43466. };
  43467. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43468. if (this._onLostFocus) {
  43469. BABYLON.Tools.UnregisterTopRootEvents([
  43470. { name: "blur", handler: this._onLostFocus }
  43471. ]);
  43472. }
  43473. if (element && this._observer) {
  43474. this.camera.getScene().onPointerObservable.remove(this._observer);
  43475. this._observer = null;
  43476. if (this._onContextMenu) {
  43477. element.removeEventListener("contextmenu", this._onContextMenu);
  43478. }
  43479. if (this._onMouseMove) {
  43480. element.removeEventListener("mousemove", this._onMouseMove);
  43481. }
  43482. if (this._onGestureStart) {
  43483. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43484. }
  43485. if (this._onGesture) {
  43486. element.removeEventListener("MSGestureChange", this._onGesture);
  43487. }
  43488. this._isPanClick = false;
  43489. this.pinchInwards = true;
  43490. this._onMouseMove = null;
  43491. this._onGestureStart = null;
  43492. this._onGesture = null;
  43493. this._MSGestureHandler = null;
  43494. this._onLostFocus = null;
  43495. this._onContextMenu = null;
  43496. }
  43497. };
  43498. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43499. return "ArcRotateCameraPointersInput";
  43500. };
  43501. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43502. return "pointers";
  43503. };
  43504. __decorate([
  43505. BABYLON.serialize()
  43506. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43507. __decorate([
  43508. BABYLON.serialize()
  43509. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43510. __decorate([
  43511. BABYLON.serialize()
  43512. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43513. __decorate([
  43514. BABYLON.serialize()
  43515. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43516. __decorate([
  43517. BABYLON.serialize()
  43518. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43519. __decorate([
  43520. BABYLON.serialize()
  43521. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43522. __decorate([
  43523. BABYLON.serialize()
  43524. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43525. __decorate([
  43526. BABYLON.serialize()
  43527. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43528. return ArcRotateCameraPointersInput;
  43529. }());
  43530. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43531. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43532. })(BABYLON || (BABYLON = {}));
  43533. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43534. var BABYLON;
  43535. (function (BABYLON) {
  43536. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43537. __extends(ArcRotateCameraInputsManager, _super);
  43538. function ArcRotateCameraInputsManager(camera) {
  43539. return _super.call(this, camera) || this;
  43540. }
  43541. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43542. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43543. return this;
  43544. };
  43545. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43546. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43547. return this;
  43548. };
  43549. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43550. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43551. return this;
  43552. };
  43553. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43554. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43555. return this;
  43556. };
  43557. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43558. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43559. return this;
  43560. };
  43561. return ArcRotateCameraInputsManager;
  43562. }(BABYLON.CameraInputsManager));
  43563. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43564. })(BABYLON || (BABYLON = {}));
  43565. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43566. var BABYLON;
  43567. (function (BABYLON) {
  43568. var ArcRotateCamera = /** @class */ (function (_super) {
  43569. __extends(ArcRotateCamera, _super);
  43570. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43571. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43572. _this.inertialAlphaOffset = 0;
  43573. _this.inertialBetaOffset = 0;
  43574. _this.inertialRadiusOffset = 0;
  43575. _this.lowerAlphaLimit = null;
  43576. _this.upperAlphaLimit = null;
  43577. _this.lowerBetaLimit = 0.01;
  43578. _this.upperBetaLimit = Math.PI;
  43579. _this.lowerRadiusLimit = null;
  43580. _this.upperRadiusLimit = null;
  43581. _this.inertialPanningX = 0;
  43582. _this.inertialPanningY = 0;
  43583. _this.pinchToPanMaxDistance = 20;
  43584. _this.panningDistanceLimit = null;
  43585. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43586. _this.panningInertia = 0.9;
  43587. //-- end properties for backward compatibility for inputs
  43588. _this.zoomOnFactor = 1;
  43589. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43590. _this.allowUpsideDown = true;
  43591. _this._viewMatrix = new BABYLON.Matrix();
  43592. // Panning
  43593. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43594. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43595. _this.checkCollisions = false;
  43596. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43597. _this._previousPosition = BABYLON.Vector3.Zero();
  43598. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43599. _this._newPosition = BABYLON.Vector3.Zero();
  43600. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43601. if (collidedMesh === void 0) { collidedMesh = null; }
  43602. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43603. newPosition.multiplyInPlace(_this._collider._radius);
  43604. }
  43605. if (!collidedMesh) {
  43606. _this._previousPosition.copyFrom(_this.position);
  43607. }
  43608. else {
  43609. _this.setPosition(newPosition);
  43610. if (_this.onCollide) {
  43611. _this.onCollide(collidedMesh);
  43612. }
  43613. }
  43614. // Recompute because of constraints
  43615. var cosa = Math.cos(_this.alpha);
  43616. var sina = Math.sin(_this.alpha);
  43617. var cosb = Math.cos(_this.beta);
  43618. var sinb = Math.sin(_this.beta);
  43619. if (sinb === 0) {
  43620. sinb = 0.0001;
  43621. }
  43622. var target = _this._getTargetPosition();
  43623. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43624. _this.position.copyFrom(_this._newPosition);
  43625. var up = _this.upVector;
  43626. if (_this.allowUpsideDown && _this.beta < 0) {
  43627. up = up.clone();
  43628. up = up.negate();
  43629. }
  43630. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43631. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43632. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43633. _this._collisionTriggered = false;
  43634. };
  43635. _this._target = BABYLON.Vector3.Zero();
  43636. if (target) {
  43637. _this.setTarget(target);
  43638. }
  43639. _this.alpha = alpha;
  43640. _this.beta = beta;
  43641. _this.radius = radius;
  43642. _this.getViewMatrix();
  43643. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43644. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43645. return _this;
  43646. }
  43647. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43648. get: function () {
  43649. return this._target;
  43650. },
  43651. set: function (value) {
  43652. this.setTarget(value);
  43653. },
  43654. enumerable: true,
  43655. configurable: true
  43656. });
  43657. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43658. //-- begin properties for backward compatibility for inputs
  43659. get: function () {
  43660. var pointers = this.inputs.attached["pointers"];
  43661. if (pointers)
  43662. return pointers.angularSensibilityX;
  43663. return 0;
  43664. },
  43665. set: function (value) {
  43666. var pointers = this.inputs.attached["pointers"];
  43667. if (pointers) {
  43668. pointers.angularSensibilityX = value;
  43669. }
  43670. },
  43671. enumerable: true,
  43672. configurable: true
  43673. });
  43674. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43675. get: function () {
  43676. var pointers = this.inputs.attached["pointers"];
  43677. if (pointers)
  43678. return pointers.angularSensibilityY;
  43679. return 0;
  43680. },
  43681. set: function (value) {
  43682. var pointers = this.inputs.attached["pointers"];
  43683. if (pointers) {
  43684. pointers.angularSensibilityY = value;
  43685. }
  43686. },
  43687. enumerable: true,
  43688. configurable: true
  43689. });
  43690. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43691. get: function () {
  43692. var pointers = this.inputs.attached["pointers"];
  43693. if (pointers)
  43694. return pointers.pinchPrecision;
  43695. return 0;
  43696. },
  43697. set: function (value) {
  43698. var pointers = this.inputs.attached["pointers"];
  43699. if (pointers) {
  43700. pointers.pinchPrecision = value;
  43701. }
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43707. get: function () {
  43708. var pointers = this.inputs.attached["pointers"];
  43709. if (pointers)
  43710. return pointers.pinchDeltaPercentage;
  43711. return 0;
  43712. },
  43713. set: function (value) {
  43714. var pointers = this.inputs.attached["pointers"];
  43715. if (pointers) {
  43716. pointers.pinchDeltaPercentage = value;
  43717. }
  43718. },
  43719. enumerable: true,
  43720. configurable: true
  43721. });
  43722. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43723. get: function () {
  43724. var pointers = this.inputs.attached["pointers"];
  43725. if (pointers)
  43726. return pointers.panningSensibility;
  43727. return 0;
  43728. },
  43729. set: function (value) {
  43730. var pointers = this.inputs.attached["pointers"];
  43731. if (pointers) {
  43732. pointers.panningSensibility = value;
  43733. }
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43739. get: function () {
  43740. var keyboard = this.inputs.attached["keyboard"];
  43741. if (keyboard)
  43742. return keyboard.keysUp;
  43743. return [];
  43744. },
  43745. set: function (value) {
  43746. var keyboard = this.inputs.attached["keyboard"];
  43747. if (keyboard)
  43748. keyboard.keysUp = value;
  43749. },
  43750. enumerable: true,
  43751. configurable: true
  43752. });
  43753. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43754. get: function () {
  43755. var keyboard = this.inputs.attached["keyboard"];
  43756. if (keyboard)
  43757. return keyboard.keysDown;
  43758. return [];
  43759. },
  43760. set: function (value) {
  43761. var keyboard = this.inputs.attached["keyboard"];
  43762. if (keyboard)
  43763. keyboard.keysDown = value;
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43769. get: function () {
  43770. var keyboard = this.inputs.attached["keyboard"];
  43771. if (keyboard)
  43772. return keyboard.keysLeft;
  43773. return [];
  43774. },
  43775. set: function (value) {
  43776. var keyboard = this.inputs.attached["keyboard"];
  43777. if (keyboard)
  43778. keyboard.keysLeft = value;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43784. get: function () {
  43785. var keyboard = this.inputs.attached["keyboard"];
  43786. if (keyboard)
  43787. return keyboard.keysRight;
  43788. return [];
  43789. },
  43790. set: function (value) {
  43791. var keyboard = this.inputs.attached["keyboard"];
  43792. if (keyboard)
  43793. keyboard.keysRight = value;
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43799. get: function () {
  43800. var mousewheel = this.inputs.attached["mousewheel"];
  43801. if (mousewheel)
  43802. return mousewheel.wheelPrecision;
  43803. return 0;
  43804. },
  43805. set: function (value) {
  43806. var mousewheel = this.inputs.attached["mousewheel"];
  43807. if (mousewheel)
  43808. mousewheel.wheelPrecision = value;
  43809. },
  43810. enumerable: true,
  43811. configurable: true
  43812. });
  43813. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43814. get: function () {
  43815. var mousewheel = this.inputs.attached["mousewheel"];
  43816. if (mousewheel)
  43817. return mousewheel.wheelDeltaPercentage;
  43818. return 0;
  43819. },
  43820. set: function (value) {
  43821. var mousewheel = this.inputs.attached["mousewheel"];
  43822. if (mousewheel)
  43823. mousewheel.wheelDeltaPercentage = value;
  43824. },
  43825. enumerable: true,
  43826. configurable: true
  43827. });
  43828. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43829. get: function () {
  43830. return this._bouncingBehavior;
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43836. get: function () {
  43837. return this._bouncingBehavior != null;
  43838. },
  43839. set: function (value) {
  43840. if (value === this.useBouncingBehavior) {
  43841. return;
  43842. }
  43843. if (value) {
  43844. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43845. this.addBehavior(this._bouncingBehavior);
  43846. }
  43847. else if (this._bouncingBehavior) {
  43848. this.removeBehavior(this._bouncingBehavior);
  43849. this._bouncingBehavior = null;
  43850. }
  43851. },
  43852. enumerable: true,
  43853. configurable: true
  43854. });
  43855. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43856. get: function () {
  43857. return this._framingBehavior;
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43863. get: function () {
  43864. return this._framingBehavior != null;
  43865. },
  43866. set: function (value) {
  43867. if (value === this.useFramingBehavior) {
  43868. return;
  43869. }
  43870. if (value) {
  43871. this._framingBehavior = new BABYLON.FramingBehavior();
  43872. this.addBehavior(this._framingBehavior);
  43873. }
  43874. else if (this._framingBehavior) {
  43875. this.removeBehavior(this._framingBehavior);
  43876. this._framingBehavior = null;
  43877. }
  43878. },
  43879. enumerable: true,
  43880. configurable: true
  43881. });
  43882. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43883. get: function () {
  43884. return this._autoRotationBehavior;
  43885. },
  43886. enumerable: true,
  43887. configurable: true
  43888. });
  43889. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  43890. get: function () {
  43891. return this._autoRotationBehavior != null;
  43892. },
  43893. set: function (value) {
  43894. if (value === this.useAutoRotationBehavior) {
  43895. return;
  43896. }
  43897. if (value) {
  43898. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  43899. this.addBehavior(this._autoRotationBehavior);
  43900. }
  43901. else if (this._autoRotationBehavior) {
  43902. this.removeBehavior(this._autoRotationBehavior);
  43903. this._autoRotationBehavior = null;
  43904. }
  43905. },
  43906. enumerable: true,
  43907. configurable: true
  43908. });
  43909. // Cache
  43910. ArcRotateCamera.prototype._initCache = function () {
  43911. _super.prototype._initCache.call(this);
  43912. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43913. this._cache.alpha = undefined;
  43914. this._cache.beta = undefined;
  43915. this._cache.radius = undefined;
  43916. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  43917. };
  43918. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  43919. if (!ignoreParentClass) {
  43920. _super.prototype._updateCache.call(this);
  43921. }
  43922. this._cache._target.copyFrom(this._getTargetPosition());
  43923. this._cache.alpha = this.alpha;
  43924. this._cache.beta = this.beta;
  43925. this._cache.radius = this.radius;
  43926. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  43927. };
  43928. ArcRotateCamera.prototype._getTargetPosition = function () {
  43929. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  43930. var pos = this._targetHost.getAbsolutePosition();
  43931. if (this._targetBoundingCenter) {
  43932. pos.addToRef(this._targetBoundingCenter, this._target);
  43933. }
  43934. else {
  43935. this._target.copyFrom(pos);
  43936. }
  43937. }
  43938. var lockedTargetPosition = this._getLockedTargetPosition();
  43939. if (lockedTargetPosition) {
  43940. return lockedTargetPosition;
  43941. }
  43942. return this._target;
  43943. };
  43944. ArcRotateCamera.prototype.storeState = function () {
  43945. this._storedAlpha = this.alpha;
  43946. this._storedBeta = this.beta;
  43947. this._storedRadius = this.radius;
  43948. this._storedTarget = this._getTargetPosition().clone();
  43949. return _super.prototype.storeState.call(this);
  43950. };
  43951. /**
  43952. * Restored camera state. You must call storeState() first
  43953. */
  43954. ArcRotateCamera.prototype._restoreStateValues = function () {
  43955. if (!_super.prototype._restoreStateValues.call(this)) {
  43956. return false;
  43957. }
  43958. this.alpha = this._storedAlpha;
  43959. this.beta = this._storedBeta;
  43960. this.radius = this._storedRadius;
  43961. this.setTarget(this._storedTarget.clone());
  43962. this.inertialAlphaOffset = 0;
  43963. this.inertialBetaOffset = 0;
  43964. this.inertialRadiusOffset = 0;
  43965. this.inertialPanningX = 0;
  43966. this.inertialPanningY = 0;
  43967. return true;
  43968. };
  43969. // Synchronized
  43970. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  43971. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  43972. return false;
  43973. return this._cache._target.equals(this._getTargetPosition())
  43974. && this._cache.alpha === this.alpha
  43975. && this._cache.beta === this.beta
  43976. && this._cache.radius === this.radius
  43977. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  43978. };
  43979. // Methods
  43980. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  43981. var _this = this;
  43982. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  43983. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  43984. this._useCtrlForPanning = useCtrlForPanning;
  43985. this._panningMouseButton = panningMouseButton;
  43986. this.inputs.attachElement(element, noPreventDefault);
  43987. this._reset = function () {
  43988. _this.inertialAlphaOffset = 0;
  43989. _this.inertialBetaOffset = 0;
  43990. _this.inertialRadiusOffset = 0;
  43991. _this.inertialPanningX = 0;
  43992. _this.inertialPanningY = 0;
  43993. };
  43994. };
  43995. ArcRotateCamera.prototype.detachControl = function (element) {
  43996. this.inputs.detachElement(element);
  43997. if (this._reset) {
  43998. this._reset();
  43999. }
  44000. };
  44001. ArcRotateCamera.prototype._checkInputs = function () {
  44002. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44003. if (this._collisionTriggered) {
  44004. return;
  44005. }
  44006. this.inputs.checkInputs();
  44007. // Inertia
  44008. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44009. if (this.getScene().useRightHandedSystem) {
  44010. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44011. }
  44012. else {
  44013. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44014. }
  44015. this.beta += this.inertialBetaOffset;
  44016. this.radius -= this.inertialRadiusOffset;
  44017. this.inertialAlphaOffset *= this.inertia;
  44018. this.inertialBetaOffset *= this.inertia;
  44019. this.inertialRadiusOffset *= this.inertia;
  44020. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44021. this.inertialAlphaOffset = 0;
  44022. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44023. this.inertialBetaOffset = 0;
  44024. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44025. this.inertialRadiusOffset = 0;
  44026. }
  44027. // Panning inertia
  44028. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44029. if (!this._localDirection) {
  44030. this._localDirection = BABYLON.Vector3.Zero();
  44031. this._transformedDirection = BABYLON.Vector3.Zero();
  44032. }
  44033. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44034. this._localDirection.multiplyInPlace(this.panningAxis);
  44035. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44036. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44037. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44038. if (!this.panningAxis.y) {
  44039. this._transformedDirection.y = 0;
  44040. }
  44041. if (!this._targetHost) {
  44042. if (this.panningDistanceLimit) {
  44043. this._transformedDirection.addInPlace(this._target);
  44044. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44045. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44046. this._target.copyFrom(this._transformedDirection);
  44047. }
  44048. }
  44049. else {
  44050. this._target.addInPlace(this._transformedDirection);
  44051. }
  44052. }
  44053. this.inertialPanningX *= this.panningInertia;
  44054. this.inertialPanningY *= this.panningInertia;
  44055. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44056. this.inertialPanningX = 0;
  44057. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44058. this.inertialPanningY = 0;
  44059. }
  44060. // Limits
  44061. this._checkLimits();
  44062. _super.prototype._checkInputs.call(this);
  44063. };
  44064. ArcRotateCamera.prototype._checkLimits = function () {
  44065. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44066. if (this.allowUpsideDown && this.beta > Math.PI) {
  44067. this.beta = this.beta - (2 * Math.PI);
  44068. }
  44069. }
  44070. else {
  44071. if (this.beta < this.lowerBetaLimit) {
  44072. this.beta = this.lowerBetaLimit;
  44073. }
  44074. }
  44075. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44076. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44077. this.beta = this.beta + (2 * Math.PI);
  44078. }
  44079. }
  44080. else {
  44081. if (this.beta > this.upperBetaLimit) {
  44082. this.beta = this.upperBetaLimit;
  44083. }
  44084. }
  44085. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44086. this.alpha = this.lowerAlphaLimit;
  44087. }
  44088. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44089. this.alpha = this.upperAlphaLimit;
  44090. }
  44091. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44092. this.radius = this.lowerRadiusLimit;
  44093. }
  44094. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44095. this.radius = this.upperRadiusLimit;
  44096. }
  44097. };
  44098. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44099. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44100. this.radius = radiusv3.length();
  44101. if (this.radius === 0) {
  44102. this.radius = 0.0001; // Just to avoid division by zero
  44103. }
  44104. // Alpha
  44105. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44106. if (radiusv3.z < 0) {
  44107. this.alpha = 2 * Math.PI - this.alpha;
  44108. }
  44109. // Beta
  44110. this.beta = Math.acos(radiusv3.y / this.radius);
  44111. this._checkLimits();
  44112. };
  44113. ArcRotateCamera.prototype.setPosition = function (position) {
  44114. if (this.position.equals(position)) {
  44115. return;
  44116. }
  44117. this.position.copyFrom(position);
  44118. this.rebuildAnglesAndRadius();
  44119. };
  44120. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44121. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44122. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44123. if (target.getBoundingInfo) {
  44124. if (toBoundingCenter) {
  44125. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44126. }
  44127. else {
  44128. this._targetBoundingCenter = null;
  44129. }
  44130. this._targetHost = target;
  44131. this._target = this._getTargetPosition();
  44132. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44133. }
  44134. else {
  44135. var newTarget = target;
  44136. var currentTarget = this._getTargetPosition();
  44137. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44138. return;
  44139. }
  44140. this._targetHost = null;
  44141. this._target = newTarget;
  44142. this._targetBoundingCenter = null;
  44143. this.onMeshTargetChangedObservable.notifyObservers(null);
  44144. }
  44145. this.rebuildAnglesAndRadius();
  44146. };
  44147. ArcRotateCamera.prototype._getViewMatrix = function () {
  44148. // Compute
  44149. var cosa = Math.cos(this.alpha);
  44150. var sina = Math.sin(this.alpha);
  44151. var cosb = Math.cos(this.beta);
  44152. var sinb = Math.sin(this.beta);
  44153. if (sinb === 0) {
  44154. sinb = 0.0001;
  44155. }
  44156. var target = this._getTargetPosition();
  44157. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44158. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44159. if (!this._collider) {
  44160. this._collider = new BABYLON.Collider();
  44161. }
  44162. this._collider._radius = this.collisionRadius;
  44163. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44164. this._collisionTriggered = true;
  44165. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44166. }
  44167. else {
  44168. this.position.copyFrom(this._newPosition);
  44169. var up = this.upVector;
  44170. if (this.allowUpsideDown && sinb < 0) {
  44171. up = up.clone();
  44172. up = up.negate();
  44173. }
  44174. if (this.getScene().useRightHandedSystem) {
  44175. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44176. }
  44177. else {
  44178. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44179. }
  44180. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44181. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44182. }
  44183. this._currentTarget = target;
  44184. return this._viewMatrix;
  44185. };
  44186. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44187. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44188. meshes = meshes || this.getScene().meshes;
  44189. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44190. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44191. this.radius = distance * this.zoomOnFactor;
  44192. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44193. };
  44194. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44195. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44196. var meshesOrMinMaxVector;
  44197. var distance;
  44198. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44199. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44200. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44201. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44202. }
  44203. else {
  44204. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44205. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44206. distance = minMaxVectorAndDistance.distance;
  44207. }
  44208. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44209. if (!doNotUpdateMaxZ) {
  44210. this.maxZ = distance * 2;
  44211. }
  44212. };
  44213. /**
  44214. * @override
  44215. * Override Camera.createRigCamera
  44216. */
  44217. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44218. var alphaShift = 0;
  44219. switch (this.cameraRigMode) {
  44220. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44222. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44223. case BABYLON.Camera.RIG_MODE_VR:
  44224. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44225. break;
  44226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44227. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44228. break;
  44229. }
  44230. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44231. rigCam._cameraRigParams = {};
  44232. return rigCam;
  44233. };
  44234. /**
  44235. * @override
  44236. * Override Camera._updateRigCameras
  44237. */
  44238. ArcRotateCamera.prototype._updateRigCameras = function () {
  44239. var camLeft = this._rigCameras[0];
  44240. var camRight = this._rigCameras[1];
  44241. camLeft.beta = camRight.beta = this.beta;
  44242. camLeft.radius = camRight.radius = this.radius;
  44243. switch (this.cameraRigMode) {
  44244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44247. case BABYLON.Camera.RIG_MODE_VR:
  44248. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44249. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44250. break;
  44251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44252. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44253. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44254. break;
  44255. }
  44256. _super.prototype._updateRigCameras.call(this);
  44257. };
  44258. ArcRotateCamera.prototype.dispose = function () {
  44259. this.inputs.clear();
  44260. _super.prototype.dispose.call(this);
  44261. };
  44262. ArcRotateCamera.prototype.getClassName = function () {
  44263. return "ArcRotateCamera";
  44264. };
  44265. __decorate([
  44266. BABYLON.serialize()
  44267. ], ArcRotateCamera.prototype, "alpha", void 0);
  44268. __decorate([
  44269. BABYLON.serialize()
  44270. ], ArcRotateCamera.prototype, "beta", void 0);
  44271. __decorate([
  44272. BABYLON.serialize()
  44273. ], ArcRotateCamera.prototype, "radius", void 0);
  44274. __decorate([
  44275. BABYLON.serializeAsVector3("target")
  44276. ], ArcRotateCamera.prototype, "_target", void 0);
  44277. __decorate([
  44278. BABYLON.serialize()
  44279. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44280. __decorate([
  44281. BABYLON.serialize()
  44282. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44283. __decorate([
  44284. BABYLON.serialize()
  44285. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44286. __decorate([
  44287. BABYLON.serialize()
  44288. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44289. __decorate([
  44290. BABYLON.serialize()
  44291. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44292. __decorate([
  44293. BABYLON.serialize()
  44294. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44295. __decorate([
  44296. BABYLON.serialize()
  44297. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44298. __decorate([
  44299. BABYLON.serialize()
  44300. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44301. __decorate([
  44302. BABYLON.serialize()
  44303. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44304. __decorate([
  44305. BABYLON.serialize()
  44306. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44307. __decorate([
  44308. BABYLON.serialize()
  44309. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44310. __decorate([
  44311. BABYLON.serialize()
  44312. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44313. __decorate([
  44314. BABYLON.serialize()
  44315. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44316. __decorate([
  44317. BABYLON.serializeAsVector3()
  44318. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44319. __decorate([
  44320. BABYLON.serialize()
  44321. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44322. __decorate([
  44323. BABYLON.serialize()
  44324. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44325. __decorate([
  44326. BABYLON.serialize()
  44327. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44328. return ArcRotateCamera;
  44329. }(BABYLON.TargetCamera));
  44330. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44331. })(BABYLON || (BABYLON = {}));
  44332. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44333. var BABYLON;
  44334. (function (BABYLON) {
  44335. /**
  44336. * The HemisphericLight simulates the ambient environment light,
  44337. * so the passed direction is the light reflection direction, not the incoming direction.
  44338. */
  44339. var HemisphericLight = /** @class */ (function (_super) {
  44340. __extends(HemisphericLight, _super);
  44341. /**
  44342. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44343. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44344. * The HemisphericLight can't cast shadows.
  44345. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44346. * @param name The friendly name of the light
  44347. * @param direction The direction of the light reflection
  44348. * @param scene The scene the light belongs to
  44349. */
  44350. function HemisphericLight(name, direction, scene) {
  44351. var _this = _super.call(this, name, scene) || this;
  44352. /**
  44353. * The groundColor is the light in the opposite direction to the one specified during creation.
  44354. * 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.
  44355. */
  44356. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44357. _this.direction = direction || BABYLON.Vector3.Up();
  44358. return _this;
  44359. }
  44360. HemisphericLight.prototype._buildUniformLayout = function () {
  44361. this._uniformBuffer.addUniform("vLightData", 4);
  44362. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44363. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44364. this._uniformBuffer.addUniform("vLightGround", 3);
  44365. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44366. this._uniformBuffer.addUniform("depthValues", 2);
  44367. this._uniformBuffer.create();
  44368. };
  44369. /**
  44370. * Returns the string "HemisphericLight".
  44371. * @return The class name
  44372. */
  44373. HemisphericLight.prototype.getClassName = function () {
  44374. return "HemisphericLight";
  44375. };
  44376. /**
  44377. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44378. * Returns the updated direction.
  44379. * @param target The target the direction should point to
  44380. * @return The computed direction
  44381. */
  44382. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44383. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44384. return this.direction;
  44385. };
  44386. /**
  44387. * Returns the shadow generator associated to the light.
  44388. * @returns Always null for hemispheric lights because it does not support shadows.
  44389. */
  44390. HemisphericLight.prototype.getShadowGenerator = function () {
  44391. return null;
  44392. };
  44393. /**
  44394. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44395. * @param effect The effect to update
  44396. * @param lightIndex The index of the light in the effect to update
  44397. * @returns The hemispheric light
  44398. */
  44399. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44400. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44401. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44402. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44403. return this;
  44404. };
  44405. /**
  44406. * @ignore internal use only.
  44407. */
  44408. HemisphericLight.prototype._getWorldMatrix = function () {
  44409. if (!this._worldMatrix) {
  44410. this._worldMatrix = BABYLON.Matrix.Identity();
  44411. }
  44412. return this._worldMatrix;
  44413. };
  44414. /**
  44415. * Returns the integer 3.
  44416. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44417. */
  44418. HemisphericLight.prototype.getTypeID = function () {
  44419. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44420. };
  44421. __decorate([
  44422. BABYLON.serializeAsColor3()
  44423. ], HemisphericLight.prototype, "groundColor", void 0);
  44424. __decorate([
  44425. BABYLON.serializeAsVector3()
  44426. ], HemisphericLight.prototype, "direction", void 0);
  44427. return HemisphericLight;
  44428. }(BABYLON.Light));
  44429. BABYLON.HemisphericLight = HemisphericLight;
  44430. })(BABYLON || (BABYLON = {}));
  44431. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44432. var BABYLON;
  44433. (function (BABYLON) {
  44434. /**
  44435. * Base implementation of @see IShadowLight
  44436. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44437. */
  44438. var ShadowLight = /** @class */ (function (_super) {
  44439. __extends(ShadowLight, _super);
  44440. function ShadowLight() {
  44441. var _this = _super !== null && _super.apply(this, arguments) || this;
  44442. _this._needProjectionMatrixCompute = true;
  44443. return _this;
  44444. }
  44445. ShadowLight.prototype._setPosition = function (value) {
  44446. this._position = value;
  44447. };
  44448. Object.defineProperty(ShadowLight.prototype, "position", {
  44449. /**
  44450. * Sets the position the shadow will be casted from. Also use as the light position for both
  44451. * point and spot lights.
  44452. */
  44453. get: function () {
  44454. return this._position;
  44455. },
  44456. /**
  44457. * Sets the position the shadow will be casted from. Also use as the light position for both
  44458. * point and spot lights.
  44459. */
  44460. set: function (value) {
  44461. this._setPosition(value);
  44462. },
  44463. enumerable: true,
  44464. configurable: true
  44465. });
  44466. ShadowLight.prototype._setDirection = function (value) {
  44467. this._direction = value;
  44468. };
  44469. Object.defineProperty(ShadowLight.prototype, "direction", {
  44470. /**
  44471. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44472. * Also use as the light direction on spot and directional lights.
  44473. */
  44474. get: function () {
  44475. return this._direction;
  44476. },
  44477. /**
  44478. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44479. * Also use as the light direction on spot and directional lights.
  44480. */
  44481. set: function (value) {
  44482. this._setDirection(value);
  44483. },
  44484. enumerable: true,
  44485. configurable: true
  44486. });
  44487. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44488. /**
  44489. * Gets the shadow projection clipping minimum z value.
  44490. */
  44491. get: function () {
  44492. return this._shadowMinZ;
  44493. },
  44494. /**
  44495. * Sets the shadow projection clipping minimum z value.
  44496. */
  44497. set: function (value) {
  44498. this._shadowMinZ = value;
  44499. this.forceProjectionMatrixCompute();
  44500. },
  44501. enumerable: true,
  44502. configurable: true
  44503. });
  44504. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44505. /**
  44506. * Sets the shadow projection clipping maximum z value.
  44507. */
  44508. get: function () {
  44509. return this._shadowMaxZ;
  44510. },
  44511. /**
  44512. * Gets the shadow projection clipping maximum z value.
  44513. */
  44514. set: function (value) {
  44515. this._shadowMaxZ = value;
  44516. this.forceProjectionMatrixCompute();
  44517. },
  44518. enumerable: true,
  44519. configurable: true
  44520. });
  44521. /**
  44522. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44523. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44524. */
  44525. ShadowLight.prototype.computeTransformedInformation = function () {
  44526. if (this.parent && this.parent.getWorldMatrix) {
  44527. if (!this.transformedPosition) {
  44528. this.transformedPosition = BABYLON.Vector3.Zero();
  44529. }
  44530. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44531. // In case the direction is present.
  44532. if (this.direction) {
  44533. if (!this.transformedDirection) {
  44534. this.transformedDirection = BABYLON.Vector3.Zero();
  44535. }
  44536. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44537. }
  44538. return true;
  44539. }
  44540. return false;
  44541. };
  44542. /**
  44543. * Return the depth scale used for the shadow map.
  44544. * @returns the depth scale.
  44545. */
  44546. ShadowLight.prototype.getDepthScale = function () {
  44547. return 50.0;
  44548. };
  44549. /**
  44550. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44551. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44552. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44553. */
  44554. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44555. return this.transformedDirection ? this.transformedDirection : this.direction;
  44556. };
  44557. /**
  44558. * Returns the ShadowLight absolute position in the World.
  44559. * @returns the position vector in world space
  44560. */
  44561. ShadowLight.prototype.getAbsolutePosition = function () {
  44562. return this.transformedPosition ? this.transformedPosition : this.position;
  44563. };
  44564. /**
  44565. * Sets the ShadowLight direction toward the passed target.
  44566. * @param target The point tot target in local space
  44567. * @returns the updated ShadowLight direction
  44568. */
  44569. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44570. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44571. return this.direction;
  44572. };
  44573. /**
  44574. * Returns the light rotation in euler definition.
  44575. * @returns the x y z rotation in local space.
  44576. */
  44577. ShadowLight.prototype.getRotation = function () {
  44578. this.direction.normalize();
  44579. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44580. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44581. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44582. };
  44583. /**
  44584. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44585. * @returns true if a cube texture needs to be use
  44586. */
  44587. ShadowLight.prototype.needCube = function () {
  44588. return false;
  44589. };
  44590. /**
  44591. * Detects if the projection matrix requires to be recomputed this frame.
  44592. * @returns true if it requires to be recomputed otherwise, false.
  44593. */
  44594. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44595. return this._needProjectionMatrixCompute;
  44596. };
  44597. /**
  44598. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44599. */
  44600. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44601. this._needProjectionMatrixCompute = true;
  44602. };
  44603. /**
  44604. * Get the world matrix of the sahdow lights.
  44605. * @ignore Internal Use Only
  44606. */
  44607. ShadowLight.prototype._getWorldMatrix = function () {
  44608. if (!this._worldMatrix) {
  44609. this._worldMatrix = BABYLON.Matrix.Identity();
  44610. }
  44611. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44612. return this._worldMatrix;
  44613. };
  44614. /**
  44615. * Gets the minZ used for shadow according to both the scene and the light.
  44616. * @param activeCamera The camera we are returning the min for
  44617. * @returns the depth min z
  44618. */
  44619. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44620. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44621. };
  44622. /**
  44623. * Gets the maxZ used for shadow according to both the scene and the light.
  44624. * @param activeCamera The camera we are returning the max for
  44625. * @returns the depth max z
  44626. */
  44627. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44628. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44629. };
  44630. /**
  44631. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44632. * @param matrix The materix to updated with the projection information
  44633. * @param viewMatrix The transform matrix of the light
  44634. * @param renderList The list of mesh to render in the map
  44635. * @returns The current light
  44636. */
  44637. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44638. if (this.customProjectionMatrixBuilder) {
  44639. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44640. }
  44641. else {
  44642. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44643. }
  44644. return this;
  44645. };
  44646. __decorate([
  44647. BABYLON.serializeAsVector3()
  44648. ], ShadowLight.prototype, "position", null);
  44649. __decorate([
  44650. BABYLON.serializeAsVector3()
  44651. ], ShadowLight.prototype, "direction", null);
  44652. __decorate([
  44653. BABYLON.serialize()
  44654. ], ShadowLight.prototype, "shadowMinZ", null);
  44655. __decorate([
  44656. BABYLON.serialize()
  44657. ], ShadowLight.prototype, "shadowMaxZ", null);
  44658. return ShadowLight;
  44659. }(BABYLON.Light));
  44660. BABYLON.ShadowLight = ShadowLight;
  44661. })(BABYLON || (BABYLON = {}));
  44662. //# sourceMappingURL=babylon.shadowLight.js.map
  44663. var BABYLON;
  44664. (function (BABYLON) {
  44665. /**
  44666. * A point light is a light defined by an unique point in world space.
  44667. * The light is emitted in every direction from this point.
  44668. * A good example of a point light is a standard light bulb.
  44669. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44670. */
  44671. var PointLight = /** @class */ (function (_super) {
  44672. __extends(PointLight, _super);
  44673. /**
  44674. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44675. * A PointLight emits the light in every direction.
  44676. * It can cast shadows.
  44677. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44678. * ```javascript
  44679. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44680. * ```
  44681. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44682. * @param name The light friendly name
  44683. * @param position The position of the point light in the scene
  44684. * @param scene The scene the lights belongs to
  44685. */
  44686. function PointLight(name, position, scene) {
  44687. var _this = _super.call(this, name, scene) || this;
  44688. _this._shadowAngle = Math.PI / 2;
  44689. _this.position = position;
  44690. return _this;
  44691. }
  44692. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44693. /**
  44694. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44695. * This specifies what angle the shadow will use to be created.
  44696. *
  44697. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44698. */
  44699. get: function () {
  44700. return this._shadowAngle;
  44701. },
  44702. /**
  44703. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44704. * This specifies what angle the shadow will use to be created.
  44705. *
  44706. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44707. */
  44708. set: function (value) {
  44709. this._shadowAngle = value;
  44710. this.forceProjectionMatrixCompute();
  44711. },
  44712. enumerable: true,
  44713. configurable: true
  44714. });
  44715. Object.defineProperty(PointLight.prototype, "direction", {
  44716. /**
  44717. * Gets the direction if it has been set.
  44718. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44719. */
  44720. get: function () {
  44721. return this._direction;
  44722. },
  44723. /**
  44724. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44725. */
  44726. set: function (value) {
  44727. var previousNeedCube = this.needCube();
  44728. this._direction = value;
  44729. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44730. this._shadowGenerator.recreateShadowMap();
  44731. }
  44732. },
  44733. enumerable: true,
  44734. configurable: true
  44735. });
  44736. /**
  44737. * Returns the string "PointLight"
  44738. * @returns the class name
  44739. */
  44740. PointLight.prototype.getClassName = function () {
  44741. return "PointLight";
  44742. };
  44743. /**
  44744. * Returns the integer 0.
  44745. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44746. */
  44747. PointLight.prototype.getTypeID = function () {
  44748. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44749. };
  44750. /**
  44751. * Specifies wether or not the shadowmap should be a cube texture.
  44752. * @returns true if the shadowmap needs to be a cube texture.
  44753. */
  44754. PointLight.prototype.needCube = function () {
  44755. return !this.direction;
  44756. };
  44757. /**
  44758. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44759. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44760. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44761. */
  44762. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44763. if (this.direction) {
  44764. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44765. }
  44766. else {
  44767. switch (faceIndex) {
  44768. case 0:
  44769. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44770. case 1:
  44771. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44772. case 2:
  44773. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44774. case 3:
  44775. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44776. case 4:
  44777. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44778. case 5:
  44779. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44780. }
  44781. }
  44782. return BABYLON.Vector3.Zero();
  44783. };
  44784. /**
  44785. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44786. * - fov = PI / 2
  44787. * - aspect ratio : 1.0
  44788. * - z-near and far equal to the active camera minZ and maxZ.
  44789. * Returns the PointLight.
  44790. */
  44791. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44792. var activeCamera = this.getScene().activeCamera;
  44793. if (!activeCamera) {
  44794. return;
  44795. }
  44796. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44797. };
  44798. PointLight.prototype._buildUniformLayout = function () {
  44799. this._uniformBuffer.addUniform("vLightData", 4);
  44800. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44801. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44802. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44803. this._uniformBuffer.addUniform("depthValues", 2);
  44804. this._uniformBuffer.create();
  44805. };
  44806. /**
  44807. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44808. * @param effect The effect to update
  44809. * @param lightIndex The index of the light in the effect to update
  44810. * @returns The point light
  44811. */
  44812. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44813. if (this.computeTransformedInformation()) {
  44814. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44815. return this;
  44816. }
  44817. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44818. return this;
  44819. };
  44820. __decorate([
  44821. BABYLON.serialize()
  44822. ], PointLight.prototype, "shadowAngle", null);
  44823. return PointLight;
  44824. }(BABYLON.ShadowLight));
  44825. BABYLON.PointLight = PointLight;
  44826. })(BABYLON || (BABYLON = {}));
  44827. //# sourceMappingURL=babylon.pointLight.js.map
  44828. var BABYLON;
  44829. (function (BABYLON) {
  44830. /**
  44831. * A directional light is defined by a direction (what a surprise!).
  44832. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44833. * 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.
  44834. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44835. */
  44836. var DirectionalLight = /** @class */ (function (_super) {
  44837. __extends(DirectionalLight, _super);
  44838. /**
  44839. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44840. * The directional light is emitted from everywhere in the given direction.
  44841. * It can cast shawdows.
  44842. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44843. * @param name The friendly name of the light
  44844. * @param direction The direction of the light
  44845. * @param scene The scene the light belongs to
  44846. */
  44847. function DirectionalLight(name, direction, scene) {
  44848. var _this = _super.call(this, name, scene) || this;
  44849. _this._shadowFrustumSize = 0;
  44850. _this._shadowOrthoScale = 0.5;
  44851. /**
  44852. * Automatically compute the projection matrix to best fit (including all the casters)
  44853. * on each frame.
  44854. */
  44855. _this.autoUpdateExtends = true;
  44856. // Cache
  44857. _this._orthoLeft = Number.MAX_VALUE;
  44858. _this._orthoRight = Number.MIN_VALUE;
  44859. _this._orthoTop = Number.MIN_VALUE;
  44860. _this._orthoBottom = Number.MAX_VALUE;
  44861. _this.position = direction.scale(-1.0);
  44862. _this.direction = direction;
  44863. return _this;
  44864. }
  44865. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44866. /**
  44867. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44868. */
  44869. get: function () {
  44870. return this._shadowFrustumSize;
  44871. },
  44872. /**
  44873. * Specifies a fix frustum size for the shadow generation.
  44874. */
  44875. set: function (value) {
  44876. this._shadowFrustumSize = value;
  44877. this.forceProjectionMatrixCompute();
  44878. },
  44879. enumerable: true,
  44880. configurable: true
  44881. });
  44882. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44883. /**
  44884. * Gets the shadow projection scale against the optimal computed one.
  44885. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44886. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44887. */
  44888. get: function () {
  44889. return this._shadowOrthoScale;
  44890. },
  44891. /**
  44892. * Sets the shadow projection scale against the optimal computed one.
  44893. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44894. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44895. */
  44896. set: function (value) {
  44897. this._shadowOrthoScale = value;
  44898. this.forceProjectionMatrixCompute();
  44899. },
  44900. enumerable: true,
  44901. configurable: true
  44902. });
  44903. /**
  44904. * Returns the string "DirectionalLight".
  44905. * @return The class name
  44906. */
  44907. DirectionalLight.prototype.getClassName = function () {
  44908. return "DirectionalLight";
  44909. };
  44910. /**
  44911. * Returns the integer 1.
  44912. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44913. */
  44914. DirectionalLight.prototype.getTypeID = function () {
  44915. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  44916. };
  44917. /**
  44918. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  44919. * Returns the DirectionalLight Shadow projection matrix.
  44920. */
  44921. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44922. if (this.shadowFrustumSize > 0) {
  44923. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  44924. }
  44925. else {
  44926. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44927. }
  44928. };
  44929. /**
  44930. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  44931. * Returns the DirectionalLight Shadow projection matrix.
  44932. */
  44933. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  44934. var activeCamera = this.getScene().activeCamera;
  44935. if (!activeCamera) {
  44936. return;
  44937. }
  44938. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  44939. };
  44940. /**
  44941. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  44942. * Returns the DirectionalLight Shadow projection matrix.
  44943. */
  44944. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44945. var activeCamera = this.getScene().activeCamera;
  44946. if (!activeCamera) {
  44947. return;
  44948. }
  44949. // Check extends
  44950. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  44951. var tempVector3 = BABYLON.Vector3.Zero();
  44952. this._orthoLeft = Number.MAX_VALUE;
  44953. this._orthoRight = Number.MIN_VALUE;
  44954. this._orthoTop = Number.MIN_VALUE;
  44955. this._orthoBottom = Number.MAX_VALUE;
  44956. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  44957. var mesh = renderList[meshIndex];
  44958. if (!mesh) {
  44959. continue;
  44960. }
  44961. var boundingInfo = mesh.getBoundingInfo();
  44962. var boundingBox = boundingInfo.boundingBox;
  44963. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  44964. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  44965. if (tempVector3.x < this._orthoLeft)
  44966. this._orthoLeft = tempVector3.x;
  44967. if (tempVector3.y < this._orthoBottom)
  44968. this._orthoBottom = tempVector3.y;
  44969. if (tempVector3.x > this._orthoRight)
  44970. this._orthoRight = tempVector3.x;
  44971. if (tempVector3.y > this._orthoTop)
  44972. this._orthoTop = tempVector3.y;
  44973. }
  44974. }
  44975. }
  44976. var xOffset = this._orthoRight - this._orthoLeft;
  44977. var yOffset = this._orthoTop - this._orthoBottom;
  44978. 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);
  44979. };
  44980. DirectionalLight.prototype._buildUniformLayout = function () {
  44981. this._uniformBuffer.addUniform("vLightData", 4);
  44982. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44983. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44984. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44985. this._uniformBuffer.addUniform("depthValues", 2);
  44986. this._uniformBuffer.create();
  44987. };
  44988. /**
  44989. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  44990. * @param effect The effect to update
  44991. * @param lightIndex The index of the light in the effect to update
  44992. * @returns The directional light
  44993. */
  44994. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  44995. if (this.computeTransformedInformation()) {
  44996. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  44997. return this;
  44998. }
  44999. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45000. return this;
  45001. };
  45002. /**
  45003. * Gets the minZ used for shadow according to both the scene and the light.
  45004. *
  45005. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45006. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45007. * @param activeCamera The camera we are returning the min for
  45008. * @returns the depth min z
  45009. */
  45010. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45011. return 1;
  45012. };
  45013. /**
  45014. * Gets the maxZ used for shadow according to both the scene and the light.
  45015. *
  45016. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45017. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45018. * @param activeCamera The camera we are returning the max for
  45019. * @returns the depth max z
  45020. */
  45021. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45022. return 1;
  45023. };
  45024. __decorate([
  45025. BABYLON.serialize()
  45026. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45027. __decorate([
  45028. BABYLON.serialize()
  45029. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45030. __decorate([
  45031. BABYLON.serialize()
  45032. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45033. return DirectionalLight;
  45034. }(BABYLON.ShadowLight));
  45035. BABYLON.DirectionalLight = DirectionalLight;
  45036. })(BABYLON || (BABYLON = {}));
  45037. //# sourceMappingURL=babylon.directionalLight.js.map
  45038. var BABYLON;
  45039. (function (BABYLON) {
  45040. /**
  45041. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45042. * These values define a cone of light starting from the position, emitting toward the direction.
  45043. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45044. * and the exponent defines the speed of the decay of the light with distance (reach).
  45045. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45046. */
  45047. var SpotLight = /** @class */ (function (_super) {
  45048. __extends(SpotLight, _super);
  45049. /**
  45050. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45051. * It can cast shadows.
  45052. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45053. * @param name The light friendly name
  45054. * @param position The position of the spot light in the scene
  45055. * @param direction The direction of the light in the scene
  45056. * @param angle The cone angle of the light in Radians
  45057. * @param exponent The light decay speed with the distance from the emission spot
  45058. * @param scene The scene the lights belongs to
  45059. */
  45060. function SpotLight(name, position, direction, angle, exponent, scene) {
  45061. var _this = _super.call(this, name, scene) || this;
  45062. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45063. _this._projectionTextureLightNear = 1e-6;
  45064. _this._projectionTextureLightFar = 1000.0;
  45065. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45066. _this._projectionTextureViewLightDirty = true;
  45067. _this._projectionTextureProjectionLightDirty = true;
  45068. _this._projectionTextureDirty = true;
  45069. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45070. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45071. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45072. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45073. _this.position = position;
  45074. _this.direction = direction;
  45075. _this.angle = angle;
  45076. _this.exponent = exponent;
  45077. return _this;
  45078. }
  45079. Object.defineProperty(SpotLight.prototype, "angle", {
  45080. /**
  45081. * Gets the cone angle of the spot light in Radians.
  45082. */
  45083. get: function () {
  45084. return this._angle;
  45085. },
  45086. /**
  45087. * Sets the cone angle of the spot light in Radians.
  45088. */
  45089. set: function (value) {
  45090. this._angle = value;
  45091. this._projectionTextureProjectionLightDirty = true;
  45092. this.forceProjectionMatrixCompute();
  45093. },
  45094. enumerable: true,
  45095. configurable: true
  45096. });
  45097. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45098. /**
  45099. * Allows scaling the angle of the light for shadow generation only.
  45100. */
  45101. get: function () {
  45102. return this._shadowAngleScale;
  45103. },
  45104. /**
  45105. * Allows scaling the angle of the light for shadow generation only.
  45106. */
  45107. set: function (value) {
  45108. this._shadowAngleScale = value;
  45109. this.forceProjectionMatrixCompute();
  45110. },
  45111. enumerable: true,
  45112. configurable: true
  45113. });
  45114. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45115. /**
  45116. * Allows reading the projecton texture
  45117. */
  45118. get: function () {
  45119. return this._projectionTextureMatrix;
  45120. },
  45121. enumerable: true,
  45122. configurable: true
  45123. });
  45124. ;
  45125. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45126. /**
  45127. * Gets the near clip of the Spotlight for texture projection.
  45128. */
  45129. get: function () {
  45130. return this._projectionTextureLightNear;
  45131. },
  45132. /**
  45133. * Sets the near clip of the Spotlight for texture projection.
  45134. */
  45135. set: function (value) {
  45136. this._projectionTextureLightNear = value;
  45137. this._projectionTextureProjectionLightDirty = true;
  45138. },
  45139. enumerable: true,
  45140. configurable: true
  45141. });
  45142. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45143. /**
  45144. * Gets the far clip of the Spotlight for texture projection.
  45145. */
  45146. get: function () {
  45147. return this._projectionTextureLightFar;
  45148. },
  45149. /**
  45150. * Sets the far clip of the Spotlight for texture projection.
  45151. */
  45152. set: function (value) {
  45153. this._projectionTextureLightFar = value;
  45154. this._projectionTextureProjectionLightDirty = true;
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45160. /**
  45161. * Gets the Up vector of the Spotlight for texture projection.
  45162. */
  45163. get: function () {
  45164. return this._projectionTextureUpDirection;
  45165. },
  45166. /**
  45167. * Sets the Up vector of the Spotlight for texture projection.
  45168. */
  45169. set: function (value) {
  45170. this._projectionTextureUpDirection = value;
  45171. this._projectionTextureProjectionLightDirty = true;
  45172. },
  45173. enumerable: true,
  45174. configurable: true
  45175. });
  45176. ;
  45177. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45178. /**
  45179. * Gets the projection texture of the light.
  45180. */
  45181. get: function () {
  45182. return this._projectionTexture;
  45183. },
  45184. /**
  45185. * Sets the projection texture of the light.
  45186. */
  45187. set: function (value) {
  45188. this._projectionTexture = value;
  45189. this._projectionTextureDirty = true;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. /**
  45195. * Returns the string "SpotLight".
  45196. * @returns the class name
  45197. */
  45198. SpotLight.prototype.getClassName = function () {
  45199. return "SpotLight";
  45200. };
  45201. /**
  45202. * Returns the integer 2.
  45203. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45204. */
  45205. SpotLight.prototype.getTypeID = function () {
  45206. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45207. };
  45208. /**
  45209. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45210. */
  45211. SpotLight.prototype._setDirection = function (value) {
  45212. _super.prototype._setDirection.call(this, value);
  45213. this._projectionTextureViewLightDirty = true;
  45214. };
  45215. /**
  45216. * Overrides the position setter to recompute the projection texture view light Matrix.
  45217. */
  45218. SpotLight.prototype._setPosition = function (value) {
  45219. _super.prototype._setPosition.call(this, value);
  45220. this._projectionTextureViewLightDirty = true;
  45221. };
  45222. /**
  45223. * 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.
  45224. * Returns the SpotLight.
  45225. */
  45226. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45227. var activeCamera = this.getScene().activeCamera;
  45228. if (!activeCamera) {
  45229. return;
  45230. }
  45231. this._shadowAngleScale = this._shadowAngleScale || 1;
  45232. var angle = this._shadowAngleScale * this._angle;
  45233. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45234. };
  45235. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45236. this._projectionTextureViewLightDirty = false;
  45237. this._projectionTextureDirty = true;
  45238. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45239. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45240. };
  45241. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45242. this._projectionTextureProjectionLightDirty = false;
  45243. this._projectionTextureDirty = true;
  45244. var light_far = this.projectionTextureLightFar;
  45245. var light_near = this.projectionTextureLightNear;
  45246. var P = light_far / (light_far - light_near);
  45247. var Q = -P * light_near;
  45248. var S = 1.0 / Math.tan(this._angle / 2.0);
  45249. var A = 1.0;
  45250. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45251. };
  45252. /**
  45253. * Main function for light texture projection matrix computing.
  45254. */
  45255. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45256. this._projectionTextureDirty = false;
  45257. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45258. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45259. };
  45260. SpotLight.prototype._buildUniformLayout = function () {
  45261. this._uniformBuffer.addUniform("vLightData", 4);
  45262. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45263. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45264. this._uniformBuffer.addUniform("vLightDirection", 3);
  45265. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45266. this._uniformBuffer.addUniform("depthValues", 2);
  45267. this._uniformBuffer.create();
  45268. };
  45269. /**
  45270. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45271. * @param effect The effect to update
  45272. * @param lightIndex The index of the light in the effect to update
  45273. * @returns The spot light
  45274. */
  45275. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45276. var normalizeDirection;
  45277. if (this.computeTransformedInformation()) {
  45278. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45279. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45280. }
  45281. else {
  45282. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45283. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45284. }
  45285. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45286. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45287. if (this._projectionTextureViewLightDirty) {
  45288. this._computeProjectionTextureViewLightMatrix();
  45289. }
  45290. if (this._projectionTextureProjectionLightDirty) {
  45291. this._computeProjectionTextureProjectionLightMatrix();
  45292. }
  45293. if (this._projectionTextureDirty) {
  45294. this._computeProjectionTextureMatrix();
  45295. }
  45296. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45297. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45298. }
  45299. return this;
  45300. };
  45301. /**
  45302. * Disposes the light and the associated resources.
  45303. */
  45304. SpotLight.prototype.dispose = function () {
  45305. _super.prototype.dispose.call(this);
  45306. if (this._projectionTexture) {
  45307. this._projectionTexture.dispose();
  45308. }
  45309. };
  45310. __decorate([
  45311. BABYLON.serialize()
  45312. ], SpotLight.prototype, "angle", null);
  45313. __decorate([
  45314. BABYLON.serialize()
  45315. ], SpotLight.prototype, "shadowAngleScale", null);
  45316. __decorate([
  45317. BABYLON.serialize()
  45318. ], SpotLight.prototype, "exponent", void 0);
  45319. __decorate([
  45320. BABYLON.serialize()
  45321. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45322. __decorate([
  45323. BABYLON.serialize()
  45324. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45328. __decorate([
  45329. BABYLON.serializeAsTexture("projectedLightTexture")
  45330. ], SpotLight.prototype, "_projectionTexture", void 0);
  45331. return SpotLight;
  45332. }(BABYLON.ShadowLight));
  45333. BABYLON.SpotLight = SpotLight;
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=babylon.spotLight.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. var AnimationRange = /** @class */ (function () {
  45339. function AnimationRange(name, from, to) {
  45340. this.name = name;
  45341. this.from = from;
  45342. this.to = to;
  45343. }
  45344. AnimationRange.prototype.clone = function () {
  45345. return new AnimationRange(this.name, this.from, this.to);
  45346. };
  45347. return AnimationRange;
  45348. }());
  45349. BABYLON.AnimationRange = AnimationRange;
  45350. /**
  45351. * Composed of a frame, and an action function
  45352. */
  45353. var AnimationEvent = /** @class */ (function () {
  45354. function AnimationEvent(frame, action, onlyOnce) {
  45355. this.frame = frame;
  45356. this.action = action;
  45357. this.onlyOnce = onlyOnce;
  45358. this.isDone = false;
  45359. }
  45360. return AnimationEvent;
  45361. }());
  45362. BABYLON.AnimationEvent = AnimationEvent;
  45363. var PathCursor = /** @class */ (function () {
  45364. function PathCursor(path) {
  45365. this.path = path;
  45366. this._onchange = new Array();
  45367. this.value = 0;
  45368. this.animations = new Array();
  45369. }
  45370. PathCursor.prototype.getPoint = function () {
  45371. var point = this.path.getPointAtLengthPosition(this.value);
  45372. return new BABYLON.Vector3(point.x, 0, point.y);
  45373. };
  45374. PathCursor.prototype.moveAhead = function (step) {
  45375. if (step === void 0) { step = 0.002; }
  45376. this.move(step);
  45377. return this;
  45378. };
  45379. PathCursor.prototype.moveBack = function (step) {
  45380. if (step === void 0) { step = 0.002; }
  45381. this.move(-step);
  45382. return this;
  45383. };
  45384. PathCursor.prototype.move = function (step) {
  45385. if (Math.abs(step) > 1) {
  45386. throw "step size should be less than 1.";
  45387. }
  45388. this.value += step;
  45389. this.ensureLimits();
  45390. this.raiseOnChange();
  45391. return this;
  45392. };
  45393. PathCursor.prototype.ensureLimits = function () {
  45394. while (this.value > 1) {
  45395. this.value -= 1;
  45396. }
  45397. while (this.value < 0) {
  45398. this.value += 1;
  45399. }
  45400. return this;
  45401. };
  45402. // used by animation engine
  45403. PathCursor.prototype.raiseOnChange = function () {
  45404. var _this = this;
  45405. this._onchange.forEach(function (f) { return f(_this); });
  45406. return this;
  45407. };
  45408. PathCursor.prototype.onchange = function (f) {
  45409. this._onchange.push(f);
  45410. return this;
  45411. };
  45412. return PathCursor;
  45413. }());
  45414. BABYLON.PathCursor = PathCursor;
  45415. var AnimationKeyInterpolation;
  45416. (function (AnimationKeyInterpolation) {
  45417. /**
  45418. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45419. */
  45420. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45421. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45422. var Animation = /** @class */ (function () {
  45423. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45424. this.name = name;
  45425. this.targetProperty = targetProperty;
  45426. this.framePerSecond = framePerSecond;
  45427. this.dataType = dataType;
  45428. this.loopMode = loopMode;
  45429. this.enableBlending = enableBlending;
  45430. this._runtimeAnimations = new Array();
  45431. // The set of event that will be linked to this animation
  45432. this._events = new Array();
  45433. this.blendingSpeed = 0.01;
  45434. this._ranges = {};
  45435. this.targetPropertyPath = targetProperty.split(".");
  45436. this.dataType = dataType;
  45437. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45438. }
  45439. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45440. var dataType = undefined;
  45441. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45442. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45443. }
  45444. else if (from instanceof BABYLON.Quaternion) {
  45445. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45446. }
  45447. else if (from instanceof BABYLON.Vector3) {
  45448. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45449. }
  45450. else if (from instanceof BABYLON.Vector2) {
  45451. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45452. }
  45453. else if (from instanceof BABYLON.Color3) {
  45454. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45455. }
  45456. else if (from instanceof BABYLON.Size) {
  45457. dataType = Animation.ANIMATIONTYPE_SIZE;
  45458. }
  45459. if (dataType == undefined) {
  45460. return null;
  45461. }
  45462. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45463. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45464. animation.setKeys(keys);
  45465. if (easingFunction !== undefined) {
  45466. animation.setEasingFunction(easingFunction);
  45467. }
  45468. return animation;
  45469. };
  45470. /**
  45471. * Sets up an animation.
  45472. * @param property the property to animate
  45473. * @param animationType the animation type to apply
  45474. * @param easingFunction the easing function used in the animation
  45475. * @returns The created animation
  45476. */
  45477. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45478. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45479. animation.setEasingFunction(easingFunction);
  45480. return animation;
  45481. };
  45482. /**
  45483. * Create and start an animation on a node
  45484. * @param {string} name defines the name of the global animation that will be run on all nodes
  45485. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45486. * @param {string} targetProperty defines property to animate
  45487. * @param {number} framePerSecond defines the number of frame per second yo use
  45488. * @param {number} totalFrame defines the number of frames in total
  45489. * @param {any} from defines the initial value
  45490. * @param {any} to defines the final value
  45491. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45492. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45493. * @param onAnimationEnd defines the callback to call when animation end
  45494. * @returns the animatable created for this animation
  45495. */
  45496. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45497. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45498. if (!animation) {
  45499. return null;
  45500. }
  45501. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45502. };
  45503. /**
  45504. * Create and start an animation on a node and its descendants
  45505. * @param {string} name defines the name of the global animation that will be run on all nodes
  45506. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45507. * @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.
  45508. * @param {string} targetProperty defines property to animate
  45509. * @param {number} framePerSecond defines the number of frame per second yo use
  45510. * @param {number} totalFrame defines the number of frames in total
  45511. * @param {any} from defines the initial value
  45512. * @param {any} to defines the final value
  45513. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45514. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45515. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45516. * @returns the list of animatables created for all nodes
  45517. * @example https://www.babylonjs-playground.com/#MH0VLI
  45518. */
  45519. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45520. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45521. if (!animation) {
  45522. return null;
  45523. }
  45524. var scene = node.getScene();
  45525. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45526. };
  45527. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45528. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45529. if (!animation) {
  45530. return null;
  45531. }
  45532. node.animations.push(animation);
  45533. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45534. };
  45535. /**
  45536. * Transition property of the Camera to the target Value.
  45537. * @param property The property to transition
  45538. * @param targetValue The target Value of the property
  45539. * @param host The object where the property to animate belongs
  45540. * @param scene Scene used to run the animation
  45541. * @param frameRate Framerate (in frame/s) to use
  45542. * @param transition The transition type we want to use
  45543. * @param duration The duration of the animation, in milliseconds
  45544. * @param onAnimationEnd Call back trigger at the end of the animation.
  45545. */
  45546. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45547. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45548. if (duration <= 0) {
  45549. host[property] = targetValue;
  45550. if (onAnimationEnd) {
  45551. onAnimationEnd();
  45552. }
  45553. return null;
  45554. }
  45555. var endFrame = frameRate * (duration / 1000);
  45556. transition.setKeys([{
  45557. frame: 0,
  45558. value: host[property].clone ? host[property].clone() : host[property]
  45559. },
  45560. {
  45561. frame: endFrame,
  45562. value: targetValue
  45563. }]);
  45564. if (!host.animations) {
  45565. host.animations = [];
  45566. }
  45567. host.animations.push(transition);
  45568. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45569. animation.onAnimationEnd = onAnimationEnd;
  45570. return animation;
  45571. };
  45572. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45573. /**
  45574. * Return the array of runtime animations currently using this animation
  45575. */
  45576. get: function () {
  45577. return this._runtimeAnimations;
  45578. },
  45579. enumerable: true,
  45580. configurable: true
  45581. });
  45582. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45583. get: function () {
  45584. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45585. var runtimeAnimation = _a[_i];
  45586. if (!runtimeAnimation.isStopped) {
  45587. return true;
  45588. }
  45589. }
  45590. return false;
  45591. },
  45592. enumerable: true,
  45593. configurable: true
  45594. });
  45595. // Methods
  45596. /**
  45597. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45598. */
  45599. Animation.prototype.toString = function (fullDetails) {
  45600. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45601. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45602. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45603. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45604. if (fullDetails) {
  45605. ret += ", Ranges: {";
  45606. var first = true;
  45607. for (var name in this._ranges) {
  45608. if (first) {
  45609. ret += ", ";
  45610. first = false;
  45611. }
  45612. ret += name;
  45613. }
  45614. ret += "}";
  45615. }
  45616. return ret;
  45617. };
  45618. /**
  45619. * Add an event to this animation.
  45620. */
  45621. Animation.prototype.addEvent = function (event) {
  45622. this._events.push(event);
  45623. };
  45624. /**
  45625. * Remove all events found at the given frame
  45626. * @param frame
  45627. */
  45628. Animation.prototype.removeEvents = function (frame) {
  45629. for (var index = 0; index < this._events.length; index++) {
  45630. if (this._events[index].frame === frame) {
  45631. this._events.splice(index, 1);
  45632. index--;
  45633. }
  45634. }
  45635. };
  45636. Animation.prototype.getEvents = function () {
  45637. return this._events;
  45638. };
  45639. Animation.prototype.createRange = function (name, from, to) {
  45640. // check name not already in use; could happen for bones after serialized
  45641. if (!this._ranges[name]) {
  45642. this._ranges[name] = new AnimationRange(name, from, to);
  45643. }
  45644. };
  45645. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45646. if (deleteFrames === void 0) { deleteFrames = true; }
  45647. var range = this._ranges[name];
  45648. if (!range) {
  45649. return;
  45650. }
  45651. if (deleteFrames) {
  45652. var from = range.from;
  45653. var to = range.to;
  45654. // this loop MUST go high to low for multiple splices to work
  45655. for (var key = this._keys.length - 1; key >= 0; key--) {
  45656. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45657. this._keys.splice(key, 1);
  45658. }
  45659. }
  45660. }
  45661. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45662. };
  45663. Animation.prototype.getRange = function (name) {
  45664. return this._ranges[name];
  45665. };
  45666. Animation.prototype.getKeys = function () {
  45667. return this._keys;
  45668. };
  45669. Animation.prototype.getHighestFrame = function () {
  45670. var ret = 0;
  45671. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45672. if (ret < this._keys[key].frame) {
  45673. ret = this._keys[key].frame;
  45674. }
  45675. }
  45676. return ret;
  45677. };
  45678. Animation.prototype.getEasingFunction = function () {
  45679. return this._easingFunction;
  45680. };
  45681. Animation.prototype.setEasingFunction = function (easingFunction) {
  45682. this._easingFunction = easingFunction;
  45683. };
  45684. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45685. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45686. };
  45687. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45688. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45689. };
  45690. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45691. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45692. };
  45693. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45694. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45695. };
  45696. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45697. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45698. };
  45699. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45700. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45701. };
  45702. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45703. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45704. };
  45705. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45706. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45707. };
  45708. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45709. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45710. };
  45711. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45712. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45713. };
  45714. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45715. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45716. };
  45717. Animation.prototype.clone = function () {
  45718. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45719. clone.enableBlending = this.enableBlending;
  45720. clone.blendingSpeed = this.blendingSpeed;
  45721. if (this._keys) {
  45722. clone.setKeys(this._keys);
  45723. }
  45724. if (this._ranges) {
  45725. clone._ranges = {};
  45726. for (var name in this._ranges) {
  45727. var range = this._ranges[name];
  45728. if (!range) {
  45729. continue;
  45730. }
  45731. clone._ranges[name] = range.clone();
  45732. }
  45733. }
  45734. return clone;
  45735. };
  45736. Animation.prototype.setKeys = function (values) {
  45737. this._keys = values.slice(0);
  45738. };
  45739. Animation.prototype.serialize = function () {
  45740. var serializationObject = {};
  45741. serializationObject.name = this.name;
  45742. serializationObject.property = this.targetProperty;
  45743. serializationObject.framePerSecond = this.framePerSecond;
  45744. serializationObject.dataType = this.dataType;
  45745. serializationObject.loopBehavior = this.loopMode;
  45746. serializationObject.enableBlending = this.enableBlending;
  45747. serializationObject.blendingSpeed = this.blendingSpeed;
  45748. var dataType = this.dataType;
  45749. serializationObject.keys = [];
  45750. var keys = this.getKeys();
  45751. for (var index = 0; index < keys.length; index++) {
  45752. var animationKey = keys[index];
  45753. var key = {};
  45754. key.frame = animationKey.frame;
  45755. switch (dataType) {
  45756. case Animation.ANIMATIONTYPE_FLOAT:
  45757. key.values = [animationKey.value];
  45758. break;
  45759. case Animation.ANIMATIONTYPE_QUATERNION:
  45760. case Animation.ANIMATIONTYPE_MATRIX:
  45761. case Animation.ANIMATIONTYPE_VECTOR3:
  45762. case Animation.ANIMATIONTYPE_COLOR3:
  45763. key.values = animationKey.value.asArray();
  45764. break;
  45765. }
  45766. serializationObject.keys.push(key);
  45767. }
  45768. serializationObject.ranges = [];
  45769. for (var name in this._ranges) {
  45770. var source = this._ranges[name];
  45771. if (!source) {
  45772. continue;
  45773. }
  45774. var range = {};
  45775. range.name = name;
  45776. range.from = source.from;
  45777. range.to = source.to;
  45778. serializationObject.ranges.push(range);
  45779. }
  45780. return serializationObject;
  45781. };
  45782. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45783. get: function () {
  45784. return Animation._ANIMATIONTYPE_FLOAT;
  45785. },
  45786. enumerable: true,
  45787. configurable: true
  45788. });
  45789. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45790. get: function () {
  45791. return Animation._ANIMATIONTYPE_VECTOR3;
  45792. },
  45793. enumerable: true,
  45794. configurable: true
  45795. });
  45796. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45797. get: function () {
  45798. return Animation._ANIMATIONTYPE_VECTOR2;
  45799. },
  45800. enumerable: true,
  45801. configurable: true
  45802. });
  45803. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45804. get: function () {
  45805. return Animation._ANIMATIONTYPE_SIZE;
  45806. },
  45807. enumerable: true,
  45808. configurable: true
  45809. });
  45810. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45811. get: function () {
  45812. return Animation._ANIMATIONTYPE_QUATERNION;
  45813. },
  45814. enumerable: true,
  45815. configurable: true
  45816. });
  45817. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45818. get: function () {
  45819. return Animation._ANIMATIONTYPE_MATRIX;
  45820. },
  45821. enumerable: true,
  45822. configurable: true
  45823. });
  45824. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45825. get: function () {
  45826. return Animation._ANIMATIONTYPE_COLOR3;
  45827. },
  45828. enumerable: true,
  45829. configurable: true
  45830. });
  45831. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45832. get: function () {
  45833. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45834. },
  45835. enumerable: true,
  45836. configurable: true
  45837. });
  45838. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45839. get: function () {
  45840. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45841. },
  45842. enumerable: true,
  45843. configurable: true
  45844. });
  45845. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45846. get: function () {
  45847. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. Animation.Parse = function (parsedAnimation) {
  45853. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45854. var dataType = parsedAnimation.dataType;
  45855. var keys = [];
  45856. var data;
  45857. var index;
  45858. if (parsedAnimation.enableBlending) {
  45859. animation.enableBlending = parsedAnimation.enableBlending;
  45860. }
  45861. if (parsedAnimation.blendingSpeed) {
  45862. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45863. }
  45864. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45865. var key = parsedAnimation.keys[index];
  45866. var inTangent;
  45867. var outTangent;
  45868. switch (dataType) {
  45869. case Animation.ANIMATIONTYPE_FLOAT:
  45870. data = key.values[0];
  45871. if (key.values.length >= 1) {
  45872. inTangent = key.values[1];
  45873. }
  45874. if (key.values.length >= 2) {
  45875. outTangent = key.values[2];
  45876. }
  45877. break;
  45878. case Animation.ANIMATIONTYPE_QUATERNION:
  45879. data = BABYLON.Quaternion.FromArray(key.values);
  45880. if (key.values.length >= 8) {
  45881. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45882. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45883. inTangent = _inTangent;
  45884. }
  45885. }
  45886. if (key.values.length >= 12) {
  45887. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45888. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45889. outTangent = _outTangent;
  45890. }
  45891. }
  45892. break;
  45893. case Animation.ANIMATIONTYPE_MATRIX:
  45894. data = BABYLON.Matrix.FromArray(key.values);
  45895. break;
  45896. case Animation.ANIMATIONTYPE_COLOR3:
  45897. data = BABYLON.Color3.FromArray(key.values);
  45898. break;
  45899. case Animation.ANIMATIONTYPE_VECTOR3:
  45900. default:
  45901. data = BABYLON.Vector3.FromArray(key.values);
  45902. break;
  45903. }
  45904. var keyData = {};
  45905. keyData.frame = key.frame;
  45906. keyData.value = data;
  45907. if (inTangent != undefined) {
  45908. keyData.inTangent = inTangent;
  45909. }
  45910. if (outTangent != undefined) {
  45911. keyData.outTangent = outTangent;
  45912. }
  45913. keys.push(keyData);
  45914. }
  45915. animation.setKeys(keys);
  45916. if (parsedAnimation.ranges) {
  45917. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  45918. data = parsedAnimation.ranges[index];
  45919. animation.createRange(data.name, data.from, data.to);
  45920. }
  45921. }
  45922. return animation;
  45923. };
  45924. Animation.AppendSerializedAnimations = function (source, destination) {
  45925. if (source.animations) {
  45926. destination.animations = [];
  45927. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  45928. var animation = source.animations[animationIndex];
  45929. destination.animations.push(animation.serialize());
  45930. }
  45931. }
  45932. };
  45933. Animation.AllowMatricesInterpolation = false;
  45934. // Statics
  45935. Animation._ANIMATIONTYPE_FLOAT = 0;
  45936. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  45937. Animation._ANIMATIONTYPE_QUATERNION = 2;
  45938. Animation._ANIMATIONTYPE_MATRIX = 3;
  45939. Animation._ANIMATIONTYPE_COLOR3 = 4;
  45940. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  45941. Animation._ANIMATIONTYPE_SIZE = 6;
  45942. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  45943. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  45944. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  45945. return Animation;
  45946. }());
  45947. BABYLON.Animation = Animation;
  45948. })(BABYLON || (BABYLON = {}));
  45949. //# sourceMappingURL=babylon.animation.js.map
  45950. var BABYLON;
  45951. (function (BABYLON) {
  45952. /**
  45953. * This class defines the direct association between an animation and a target
  45954. */
  45955. var TargetedAnimation = /** @class */ (function () {
  45956. function TargetedAnimation() {
  45957. }
  45958. return TargetedAnimation;
  45959. }());
  45960. BABYLON.TargetedAnimation = TargetedAnimation;
  45961. /**
  45962. * Use this class to create coordinated animations on multiple targets
  45963. */
  45964. var AnimationGroup = /** @class */ (function () {
  45965. function AnimationGroup(name, scene) {
  45966. if (scene === void 0) { scene = null; }
  45967. this.name = name;
  45968. this._targetedAnimations = new Array();
  45969. this._animatables = new Array();
  45970. this._from = Number.MAX_VALUE;
  45971. this._to = -Number.MAX_VALUE;
  45972. this._speedRatio = 1;
  45973. this.onAnimationEndObservable = new BABYLON.Observable();
  45974. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45975. this._scene.animationGroups.push(this);
  45976. }
  45977. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  45978. /**
  45979. * Define if the animations are started
  45980. */
  45981. get: function () {
  45982. return this._isStarted;
  45983. },
  45984. enumerable: true,
  45985. configurable: true
  45986. });
  45987. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  45988. /**
  45989. * Gets or sets the speed ratio to use for all animations
  45990. */
  45991. get: function () {
  45992. return this._speedRatio;
  45993. },
  45994. /**
  45995. * Gets or sets the speed ratio to use for all animations
  45996. */
  45997. set: function (value) {
  45998. if (this._speedRatio === value) {
  45999. return;
  46000. }
  46001. this._speedRatio = value;
  46002. for (var index = 0; index < this._animatables.length; index++) {
  46003. var animatable = this._animatables[index];
  46004. animatable.speedRatio = this._speedRatio;
  46005. }
  46006. },
  46007. enumerable: true,
  46008. configurable: true
  46009. });
  46010. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46011. /**
  46012. * Gets the targeted animations for this animation group
  46013. */
  46014. get: function () {
  46015. return this._targetedAnimations;
  46016. },
  46017. enumerable: true,
  46018. configurable: true
  46019. });
  46020. /**
  46021. * Add an animation (with its target) in the group
  46022. * @param animation defines the animation we want to add
  46023. * @param target defines the target of the animation
  46024. * @returns the {BABYLON.TargetedAnimation} object
  46025. */
  46026. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46027. var targetedAnimation = {
  46028. animation: animation,
  46029. target: target
  46030. };
  46031. var keys = animation.getKeys();
  46032. if (this._from > keys[0].frame) {
  46033. this._from = keys[0].frame;
  46034. }
  46035. if (this._to < keys[keys.length - 1].frame) {
  46036. this._to = keys[keys.length - 1].frame;
  46037. }
  46038. this._targetedAnimations.push(targetedAnimation);
  46039. return targetedAnimation;
  46040. };
  46041. /**
  46042. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46043. * It can add constant keys at begin or end
  46044. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46045. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46046. */
  46047. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46048. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46049. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46050. beginFrame = Math.max(beginFrame, this._from);
  46051. endFrame = Math.min(endFrame, this._to);
  46052. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46053. var targetedAnimation = this._targetedAnimations[index];
  46054. var keys = targetedAnimation.animation.getKeys();
  46055. var startKey = keys[0];
  46056. var endKey = keys[keys.length - 1];
  46057. if (startKey.frame > beginFrame) {
  46058. var newKey = {
  46059. frame: beginFrame,
  46060. value: startKey.value,
  46061. inTangent: startKey.inTangent,
  46062. outTangent: startKey.outTangent,
  46063. interpolation: startKey.interpolation
  46064. };
  46065. keys.splice(0, 0, newKey);
  46066. }
  46067. if (endKey.frame < endFrame) {
  46068. var newKey = {
  46069. frame: endFrame,
  46070. value: endKey.value,
  46071. inTangent: endKey.outTangent,
  46072. outTangent: endKey.outTangent,
  46073. interpolation: endKey.interpolation
  46074. };
  46075. keys.push(newKey);
  46076. }
  46077. }
  46078. return this;
  46079. };
  46080. /**
  46081. * Start all animations on given targets
  46082. * @param loop defines if animations must loop
  46083. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46084. */
  46085. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46086. var _this = this;
  46087. if (loop === void 0) { loop = false; }
  46088. if (speedRatio === void 0) { speedRatio = 1; }
  46089. if (this._isStarted || this._targetedAnimations.length === 0) {
  46090. return this;
  46091. }
  46092. var _loop_1 = function () {
  46093. var targetedAnimation = this_1._targetedAnimations[index];
  46094. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46095. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46096. }));
  46097. };
  46098. var this_1 = this;
  46099. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46100. _loop_1();
  46101. }
  46102. this._speedRatio = speedRatio;
  46103. this._isStarted = true;
  46104. return this;
  46105. };
  46106. /**
  46107. * Pause all animations
  46108. */
  46109. AnimationGroup.prototype.pause = function () {
  46110. if (!this._isStarted) {
  46111. return this;
  46112. }
  46113. for (var index = 0; index < this._animatables.length; index++) {
  46114. var animatable = this._animatables[index];
  46115. animatable.pause();
  46116. }
  46117. return this;
  46118. };
  46119. /**
  46120. * Play all animations to initial state
  46121. * This function will start() the animations if they were not started or will restart() them if they were paused
  46122. * @param loop defines if animations must loop
  46123. */
  46124. AnimationGroup.prototype.play = function (loop) {
  46125. if (this.isStarted) {
  46126. if (loop !== undefined) {
  46127. for (var index = 0; index < this._animatables.length; index++) {
  46128. var animatable = this._animatables[index];
  46129. animatable.loopAnimation = loop;
  46130. }
  46131. }
  46132. this.restart();
  46133. }
  46134. else {
  46135. this.start(loop, this._speedRatio);
  46136. }
  46137. return this;
  46138. };
  46139. /**
  46140. * Reset all animations to initial state
  46141. */
  46142. AnimationGroup.prototype.reset = function () {
  46143. if (!this._isStarted) {
  46144. return this;
  46145. }
  46146. for (var index = 0; index < this._animatables.length; index++) {
  46147. var animatable = this._animatables[index];
  46148. animatable.reset();
  46149. }
  46150. return this;
  46151. };
  46152. /**
  46153. * Restart animations from key 0
  46154. */
  46155. AnimationGroup.prototype.restart = function () {
  46156. if (!this._isStarted) {
  46157. return this;
  46158. }
  46159. for (var index = 0; index < this._animatables.length; index++) {
  46160. var animatable = this._animatables[index];
  46161. animatable.restart();
  46162. }
  46163. return this;
  46164. };
  46165. /**
  46166. * Stop all animations
  46167. */
  46168. AnimationGroup.prototype.stop = function () {
  46169. if (!this._isStarted) {
  46170. return this;
  46171. }
  46172. for (var index = 0; index < this._animatables.length; index++) {
  46173. var animatable = this._animatables[index];
  46174. animatable.stop();
  46175. }
  46176. this._isStarted = false;
  46177. return this;
  46178. };
  46179. /**
  46180. * Dispose all associated resources
  46181. */
  46182. AnimationGroup.prototype.dispose = function () {
  46183. this._targetedAnimations = [];
  46184. this._animatables = [];
  46185. var index = this._scene.animationGroups.indexOf(this);
  46186. if (index > -1) {
  46187. this._scene.animationGroups.splice(index, 1);
  46188. }
  46189. };
  46190. return AnimationGroup;
  46191. }());
  46192. BABYLON.AnimationGroup = AnimationGroup;
  46193. })(BABYLON || (BABYLON = {}));
  46194. //# sourceMappingURL=babylon.animationGroup.js.map
  46195. var BABYLON;
  46196. (function (BABYLON) {
  46197. var RuntimeAnimation = /** @class */ (function () {
  46198. function RuntimeAnimation(target, animation) {
  46199. this._offsetsCache = {};
  46200. this._highLimitsCache = {};
  46201. this._stopped = false;
  46202. this._blendingFactor = 0;
  46203. this._ratioOffset = 0;
  46204. this._animation = animation;
  46205. this._target = target;
  46206. animation._runtimeAnimations.push(this);
  46207. }
  46208. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46209. get: function () {
  46210. return this._animation;
  46211. },
  46212. enumerable: true,
  46213. configurable: true
  46214. });
  46215. RuntimeAnimation.prototype.reset = function () {
  46216. this._offsetsCache = {};
  46217. this._highLimitsCache = {};
  46218. this.currentFrame = 0;
  46219. this._blendingFactor = 0;
  46220. this._originalBlendValue = null;
  46221. };
  46222. RuntimeAnimation.prototype.isStopped = function () {
  46223. return this._stopped;
  46224. };
  46225. RuntimeAnimation.prototype.dispose = function () {
  46226. var index = this._animation.runtimeAnimations.indexOf(this);
  46227. if (index > -1) {
  46228. this._animation.runtimeAnimations.splice(index, 1);
  46229. }
  46230. };
  46231. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46232. if (typeof value === "function") {
  46233. return value();
  46234. }
  46235. return value;
  46236. };
  46237. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46238. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46239. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46240. }
  46241. this.currentFrame = currentFrame;
  46242. var keys = this._animation.getKeys();
  46243. // Try to get a hash to find the right key
  46244. 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));
  46245. if (keys[startKeyIndex].frame >= currentFrame) {
  46246. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46247. startKeyIndex--;
  46248. }
  46249. }
  46250. for (var key = startKeyIndex; key < keys.length; key++) {
  46251. var endKey = keys[key + 1];
  46252. if (endKey.frame >= currentFrame) {
  46253. var startKey = keys[key];
  46254. var startValue = this._getKeyValue(startKey.value);
  46255. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46256. return startValue;
  46257. }
  46258. var endValue = this._getKeyValue(endKey.value);
  46259. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46260. var frameDelta = endKey.frame - startKey.frame;
  46261. // gradient : percent of currentFrame between the frame inf and the frame sup
  46262. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46263. // check for easingFunction and correction of gradient
  46264. var easingFunction = this._animation.getEasingFunction();
  46265. if (easingFunction != null) {
  46266. gradient = easingFunction.ease(gradient);
  46267. }
  46268. switch (this._animation.dataType) {
  46269. // Float
  46270. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46271. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46272. switch (loopMode) {
  46273. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46274. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46275. return floatValue;
  46276. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46277. return offsetValue * repeatCount + floatValue;
  46278. }
  46279. break;
  46280. // Quaternion
  46281. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46282. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46283. switch (loopMode) {
  46284. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46285. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46286. return quatValue;
  46287. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46288. return quatValue.add(offsetValue.scale(repeatCount));
  46289. }
  46290. return quatValue;
  46291. // Vector3
  46292. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46293. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46294. switch (loopMode) {
  46295. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46296. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46297. return vec3Value;
  46298. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46299. return vec3Value.add(offsetValue.scale(repeatCount));
  46300. }
  46301. // Vector2
  46302. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46303. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46304. switch (loopMode) {
  46305. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46306. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46307. return vec2Value;
  46308. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46309. return vec2Value.add(offsetValue.scale(repeatCount));
  46310. }
  46311. // Size
  46312. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46313. switch (loopMode) {
  46314. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46315. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46316. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46317. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46318. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46319. }
  46320. // Color3
  46321. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46322. switch (loopMode) {
  46323. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46324. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46325. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46326. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46327. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46328. }
  46329. // Matrix
  46330. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46331. switch (loopMode) {
  46332. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46333. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46334. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46335. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46336. }
  46337. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46338. return startValue;
  46339. }
  46340. default:
  46341. break;
  46342. }
  46343. break;
  46344. }
  46345. }
  46346. return this._getKeyValue(keys[keys.length - 1].value);
  46347. };
  46348. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46349. if (blend === void 0) { blend = false; }
  46350. // Set value
  46351. var path;
  46352. var destination;
  46353. var targetPropertyPath = this._animation.targetPropertyPath;
  46354. if (targetPropertyPath.length > 1) {
  46355. var property = this._target[targetPropertyPath[0]];
  46356. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46357. property = property[targetPropertyPath[index]];
  46358. }
  46359. path = targetPropertyPath[targetPropertyPath.length - 1];
  46360. destination = property;
  46361. }
  46362. else {
  46363. path = targetPropertyPath[0];
  46364. destination = this._target;
  46365. }
  46366. // Blending
  46367. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46368. if (!this._originalBlendValue) {
  46369. if (destination[path].clone) {
  46370. this._originalBlendValue = destination[path].clone();
  46371. }
  46372. else {
  46373. this._originalBlendValue = destination[path];
  46374. }
  46375. }
  46376. if (this._originalBlendValue.prototype) {
  46377. if (this._originalBlendValue.prototype.Lerp) {
  46378. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46379. }
  46380. else {
  46381. destination[path] = currentValue;
  46382. }
  46383. }
  46384. else if (this._originalBlendValue.m) {
  46385. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46386. }
  46387. else {
  46388. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46389. }
  46390. this._blendingFactor += this._animation.blendingSpeed;
  46391. }
  46392. else {
  46393. destination[path] = currentValue;
  46394. }
  46395. if (this._target.markAsDirty) {
  46396. this._target.markAsDirty(this._animation.targetProperty);
  46397. }
  46398. };
  46399. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46400. var keys = this._animation.getKeys();
  46401. if (frame < keys[0].frame) {
  46402. frame = keys[0].frame;
  46403. }
  46404. else if (frame > keys[keys.length - 1].frame) {
  46405. frame = keys[keys.length - 1].frame;
  46406. }
  46407. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46408. this.setValue(currentValue);
  46409. };
  46410. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46411. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46412. this._ratioOffset = this._previousRatio - newRatio;
  46413. };
  46414. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46415. if (blend === void 0) { blend = false; }
  46416. var targetPropertyPath = this._animation.targetPropertyPath;
  46417. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46418. this._stopped = true;
  46419. return false;
  46420. }
  46421. var returnValue = true;
  46422. var keys = this._animation.getKeys();
  46423. // Adding a start key at frame 0 if missing
  46424. if (keys[0].frame !== 0) {
  46425. var newKey = { frame: 0, value: keys[0].value };
  46426. keys.splice(0, 0, newKey);
  46427. }
  46428. // Check limits
  46429. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46430. from = keys[0].frame;
  46431. }
  46432. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46433. to = keys[keys.length - 1].frame;
  46434. }
  46435. //to and from cannot be the same key
  46436. if (from === to) {
  46437. if (from > keys[0].frame) {
  46438. from--;
  46439. }
  46440. else if (to < keys[keys.length - 1].frame) {
  46441. to++;
  46442. }
  46443. }
  46444. // Compute ratio
  46445. var range = to - from;
  46446. var offsetValue;
  46447. // ratio represents the frame delta between from and to
  46448. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46449. var highLimitValue = 0;
  46450. this._previousDelay = delay;
  46451. this._previousRatio = ratio;
  46452. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46453. returnValue = false;
  46454. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46455. }
  46456. else {
  46457. // Get max value if required
  46458. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46459. var keyOffset = to.toString() + from.toString();
  46460. if (!this._offsetsCache[keyOffset]) {
  46461. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46462. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46463. switch (this._animation.dataType) {
  46464. // Float
  46465. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46466. this._offsetsCache[keyOffset] = toValue - fromValue;
  46467. break;
  46468. // Quaternion
  46469. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46470. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46471. break;
  46472. // Vector3
  46473. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46474. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46475. // Vector2
  46476. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46477. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46478. // Size
  46479. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46480. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46481. // Color3
  46482. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46483. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46484. default:
  46485. break;
  46486. }
  46487. this._highLimitsCache[keyOffset] = toValue;
  46488. }
  46489. highLimitValue = this._highLimitsCache[keyOffset];
  46490. offsetValue = this._offsetsCache[keyOffset];
  46491. }
  46492. }
  46493. if (offsetValue === undefined) {
  46494. switch (this._animation.dataType) {
  46495. // Float
  46496. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46497. offsetValue = 0;
  46498. break;
  46499. // Quaternion
  46500. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46501. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46502. break;
  46503. // Vector3
  46504. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46505. offsetValue = BABYLON.Vector3.Zero();
  46506. break;
  46507. // Vector2
  46508. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46509. offsetValue = BABYLON.Vector2.Zero();
  46510. break;
  46511. // Size
  46512. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46513. offsetValue = BABYLON.Size.Zero();
  46514. break;
  46515. // Color3
  46516. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46517. offsetValue = BABYLON.Color3.Black();
  46518. }
  46519. }
  46520. // Compute value
  46521. var repeatCount = (ratio / range) >> 0;
  46522. var currentFrame = returnValue ? from + ratio % range : to;
  46523. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46524. // Set value
  46525. this.setValue(currentValue);
  46526. // Check events
  46527. var events = this._animation.getEvents();
  46528. for (var index = 0; index < events.length; index++) {
  46529. // Make sure current frame has passed event frame and that event frame is within the current range
  46530. // Also, handle both forward and reverse animations
  46531. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46532. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46533. var event = events[index];
  46534. if (!event.isDone) {
  46535. // If event should be done only once, remove it.
  46536. if (event.onlyOnce) {
  46537. events.splice(index, 1);
  46538. index--;
  46539. }
  46540. event.isDone = true;
  46541. event.action();
  46542. } // Don't do anything if the event has already be done.
  46543. }
  46544. else if (events[index].isDone && !events[index].onlyOnce) {
  46545. // reset event, the animation is looping
  46546. events[index].isDone = false;
  46547. }
  46548. }
  46549. if (!returnValue) {
  46550. this._stopped = true;
  46551. }
  46552. return returnValue;
  46553. };
  46554. return RuntimeAnimation;
  46555. }());
  46556. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46557. })(BABYLON || (BABYLON = {}));
  46558. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46559. var BABYLON;
  46560. (function (BABYLON) {
  46561. var Animatable = /** @class */ (function () {
  46562. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46563. if (fromFrame === void 0) { fromFrame = 0; }
  46564. if (toFrame === void 0) { toFrame = 100; }
  46565. if (loopAnimation === void 0) { loopAnimation = false; }
  46566. if (speedRatio === void 0) { speedRatio = 1.0; }
  46567. this.target = target;
  46568. this.fromFrame = fromFrame;
  46569. this.toFrame = toFrame;
  46570. this.loopAnimation = loopAnimation;
  46571. this.onAnimationEnd = onAnimationEnd;
  46572. this._localDelayOffset = null;
  46573. this._pausedDelay = null;
  46574. this._runtimeAnimations = new Array();
  46575. this._paused = false;
  46576. this._speedRatio = 1;
  46577. this.animationStarted = false;
  46578. if (animations) {
  46579. this.appendAnimations(target, animations);
  46580. }
  46581. this._speedRatio = speedRatio;
  46582. this._scene = scene;
  46583. scene._activeAnimatables.push(this);
  46584. }
  46585. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46586. get: function () {
  46587. return this._speedRatio;
  46588. },
  46589. set: function (value) {
  46590. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46591. var animation = this._runtimeAnimations[index];
  46592. animation._prepareForSpeedRatioChange(value);
  46593. }
  46594. this._speedRatio = value;
  46595. },
  46596. enumerable: true,
  46597. configurable: true
  46598. });
  46599. // Methods
  46600. Animatable.prototype.getAnimations = function () {
  46601. return this._runtimeAnimations;
  46602. };
  46603. Animatable.prototype.appendAnimations = function (target, animations) {
  46604. for (var index = 0; index < animations.length; index++) {
  46605. var animation = animations[index];
  46606. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46607. }
  46608. };
  46609. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46610. var runtimeAnimations = this._runtimeAnimations;
  46611. for (var index = 0; index < runtimeAnimations.length; index++) {
  46612. if (runtimeAnimations[index].animation.targetProperty === property) {
  46613. return runtimeAnimations[index].animation;
  46614. }
  46615. }
  46616. return null;
  46617. };
  46618. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46619. var runtimeAnimations = this._runtimeAnimations;
  46620. for (var index = 0; index < runtimeAnimations.length; index++) {
  46621. if (runtimeAnimations[index].animation.targetProperty === property) {
  46622. return runtimeAnimations[index];
  46623. }
  46624. }
  46625. return null;
  46626. };
  46627. Animatable.prototype.reset = function () {
  46628. var runtimeAnimations = this._runtimeAnimations;
  46629. for (var index = 0; index < runtimeAnimations.length; index++) {
  46630. runtimeAnimations[index].reset();
  46631. }
  46632. // Reset to original value
  46633. for (index = 0; index < runtimeAnimations.length; index++) {
  46634. var animation = runtimeAnimations[index];
  46635. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46636. }
  46637. this._localDelayOffset = null;
  46638. this._pausedDelay = null;
  46639. };
  46640. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46641. var runtimeAnimations = this._runtimeAnimations;
  46642. for (var index = 0; index < runtimeAnimations.length; index++) {
  46643. runtimeAnimations[index].animation.enableBlending = true;
  46644. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46645. }
  46646. };
  46647. Animatable.prototype.disableBlending = function () {
  46648. var runtimeAnimations = this._runtimeAnimations;
  46649. for (var index = 0; index < runtimeAnimations.length; index++) {
  46650. runtimeAnimations[index].animation.enableBlending = false;
  46651. }
  46652. };
  46653. Animatable.prototype.goToFrame = function (frame) {
  46654. var runtimeAnimations = this._runtimeAnimations;
  46655. if (runtimeAnimations[0]) {
  46656. var fps = runtimeAnimations[0].animation.framePerSecond;
  46657. var currentFrame = runtimeAnimations[0].currentFrame;
  46658. var adjustTime = frame - currentFrame;
  46659. var delay = adjustTime * 1000 / fps;
  46660. if (this._localDelayOffset === null) {
  46661. this._localDelayOffset = 0;
  46662. }
  46663. this._localDelayOffset -= delay;
  46664. }
  46665. for (var index = 0; index < runtimeAnimations.length; index++) {
  46666. runtimeAnimations[index].goToFrame(frame);
  46667. }
  46668. };
  46669. Animatable.prototype.pause = function () {
  46670. if (this._paused) {
  46671. return;
  46672. }
  46673. this._paused = true;
  46674. };
  46675. Animatable.prototype.restart = function () {
  46676. this._paused = false;
  46677. };
  46678. Animatable.prototype.stop = function (animationName) {
  46679. if (animationName) {
  46680. var idx = this._scene._activeAnimatables.indexOf(this);
  46681. if (idx > -1) {
  46682. var runtimeAnimations = this._runtimeAnimations;
  46683. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46684. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46685. continue;
  46686. }
  46687. runtimeAnimations[index].dispose();
  46688. runtimeAnimations.splice(index, 1);
  46689. }
  46690. if (runtimeAnimations.length == 0) {
  46691. this._scene._activeAnimatables.splice(idx, 1);
  46692. if (this.onAnimationEnd) {
  46693. this.onAnimationEnd();
  46694. }
  46695. }
  46696. }
  46697. }
  46698. else {
  46699. var index = this._scene._activeAnimatables.indexOf(this);
  46700. if (index > -1) {
  46701. this._scene._activeAnimatables.splice(index, 1);
  46702. var runtimeAnimations = this._runtimeAnimations;
  46703. for (var index = 0; index < runtimeAnimations.length; index++) {
  46704. runtimeAnimations[index].dispose();
  46705. }
  46706. if (this.onAnimationEnd) {
  46707. this.onAnimationEnd();
  46708. }
  46709. }
  46710. }
  46711. };
  46712. Animatable.prototype._animate = function (delay) {
  46713. if (this._paused) {
  46714. this.animationStarted = false;
  46715. if (this._pausedDelay === null) {
  46716. this._pausedDelay = delay;
  46717. }
  46718. return true;
  46719. }
  46720. if (this._localDelayOffset === null) {
  46721. this._localDelayOffset = delay;
  46722. this._pausedDelay = null;
  46723. }
  46724. else if (this._pausedDelay !== null) {
  46725. this._localDelayOffset += delay - this._pausedDelay;
  46726. this._pausedDelay = null;
  46727. }
  46728. // Animating
  46729. var running = false;
  46730. var runtimeAnimations = this._runtimeAnimations;
  46731. var index;
  46732. for (index = 0; index < runtimeAnimations.length; index++) {
  46733. var animation = runtimeAnimations[index];
  46734. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46735. running = running || isRunning;
  46736. }
  46737. this.animationStarted = running;
  46738. if (!running) {
  46739. // Remove from active animatables
  46740. index = this._scene._activeAnimatables.indexOf(this);
  46741. this._scene._activeAnimatables.splice(index, 1);
  46742. // Dispose all runtime animations
  46743. for (index = 0; index < runtimeAnimations.length; index++) {
  46744. runtimeAnimations[index].dispose();
  46745. }
  46746. }
  46747. if (!running && this.onAnimationEnd) {
  46748. this.onAnimationEnd();
  46749. this.onAnimationEnd = null;
  46750. }
  46751. return running;
  46752. };
  46753. return Animatable;
  46754. }());
  46755. BABYLON.Animatable = Animatable;
  46756. })(BABYLON || (BABYLON = {}));
  46757. //# sourceMappingURL=babylon.animatable.js.map
  46758. var BABYLON;
  46759. (function (BABYLON) {
  46760. var EasingFunction = /** @class */ (function () {
  46761. function EasingFunction() {
  46762. // Properties
  46763. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46764. }
  46765. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46766. get: function () {
  46767. return EasingFunction._EASINGMODE_EASEIN;
  46768. },
  46769. enumerable: true,
  46770. configurable: true
  46771. });
  46772. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46773. get: function () {
  46774. return EasingFunction._EASINGMODE_EASEOUT;
  46775. },
  46776. enumerable: true,
  46777. configurable: true
  46778. });
  46779. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46780. get: function () {
  46781. return EasingFunction._EASINGMODE_EASEINOUT;
  46782. },
  46783. enumerable: true,
  46784. configurable: true
  46785. });
  46786. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46787. var n = Math.min(Math.max(easingMode, 0), 2);
  46788. this._easingMode = n;
  46789. };
  46790. EasingFunction.prototype.getEasingMode = function () {
  46791. return this._easingMode;
  46792. };
  46793. EasingFunction.prototype.easeInCore = function (gradient) {
  46794. throw new Error('You must implement this method');
  46795. };
  46796. EasingFunction.prototype.ease = function (gradient) {
  46797. switch (this._easingMode) {
  46798. case EasingFunction.EASINGMODE_EASEIN:
  46799. return this.easeInCore(gradient);
  46800. case EasingFunction.EASINGMODE_EASEOUT:
  46801. return (1 - this.easeInCore(1 - gradient));
  46802. }
  46803. if (gradient >= 0.5) {
  46804. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46805. }
  46806. return (this.easeInCore(gradient * 2) * 0.5);
  46807. };
  46808. //Statics
  46809. EasingFunction._EASINGMODE_EASEIN = 0;
  46810. EasingFunction._EASINGMODE_EASEOUT = 1;
  46811. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46812. return EasingFunction;
  46813. }());
  46814. BABYLON.EasingFunction = EasingFunction;
  46815. var CircleEase = /** @class */ (function (_super) {
  46816. __extends(CircleEase, _super);
  46817. function CircleEase() {
  46818. return _super !== null && _super.apply(this, arguments) || this;
  46819. }
  46820. CircleEase.prototype.easeInCore = function (gradient) {
  46821. gradient = Math.max(0, Math.min(1, gradient));
  46822. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46823. };
  46824. return CircleEase;
  46825. }(EasingFunction));
  46826. BABYLON.CircleEase = CircleEase;
  46827. var BackEase = /** @class */ (function (_super) {
  46828. __extends(BackEase, _super);
  46829. function BackEase(amplitude) {
  46830. if (amplitude === void 0) { amplitude = 1; }
  46831. var _this = _super.call(this) || this;
  46832. _this.amplitude = amplitude;
  46833. return _this;
  46834. }
  46835. BackEase.prototype.easeInCore = function (gradient) {
  46836. var num = Math.max(0, this.amplitude);
  46837. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46838. };
  46839. return BackEase;
  46840. }(EasingFunction));
  46841. BABYLON.BackEase = BackEase;
  46842. var BounceEase = /** @class */ (function (_super) {
  46843. __extends(BounceEase, _super);
  46844. function BounceEase(bounces, bounciness) {
  46845. if (bounces === void 0) { bounces = 3; }
  46846. if (bounciness === void 0) { bounciness = 2; }
  46847. var _this = _super.call(this) || this;
  46848. _this.bounces = bounces;
  46849. _this.bounciness = bounciness;
  46850. return _this;
  46851. }
  46852. BounceEase.prototype.easeInCore = function (gradient) {
  46853. var y = Math.max(0.0, this.bounces);
  46854. var bounciness = this.bounciness;
  46855. if (bounciness <= 1.0) {
  46856. bounciness = 1.001;
  46857. }
  46858. var num9 = Math.pow(bounciness, y);
  46859. var num5 = 1.0 - bounciness;
  46860. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46861. var num15 = gradient * num4;
  46862. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46863. var num3 = Math.floor(num65);
  46864. var num13 = num3 + 1.0;
  46865. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46866. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46867. var num7 = (num8 + num12) * 0.5;
  46868. var num6 = gradient - num7;
  46869. var num2 = num7 - num8;
  46870. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46871. };
  46872. return BounceEase;
  46873. }(EasingFunction));
  46874. BABYLON.BounceEase = BounceEase;
  46875. var CubicEase = /** @class */ (function (_super) {
  46876. __extends(CubicEase, _super);
  46877. function CubicEase() {
  46878. return _super !== null && _super.apply(this, arguments) || this;
  46879. }
  46880. CubicEase.prototype.easeInCore = function (gradient) {
  46881. return (gradient * gradient * gradient);
  46882. };
  46883. return CubicEase;
  46884. }(EasingFunction));
  46885. BABYLON.CubicEase = CubicEase;
  46886. var ElasticEase = /** @class */ (function (_super) {
  46887. __extends(ElasticEase, _super);
  46888. function ElasticEase(oscillations, springiness) {
  46889. if (oscillations === void 0) { oscillations = 3; }
  46890. if (springiness === void 0) { springiness = 3; }
  46891. var _this = _super.call(this) || this;
  46892. _this.oscillations = oscillations;
  46893. _this.springiness = springiness;
  46894. return _this;
  46895. }
  46896. ElasticEase.prototype.easeInCore = function (gradient) {
  46897. var num2;
  46898. var num3 = Math.max(0.0, this.oscillations);
  46899. var num = Math.max(0.0, this.springiness);
  46900. if (num == 0) {
  46901. num2 = gradient;
  46902. }
  46903. else {
  46904. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  46905. }
  46906. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  46907. };
  46908. return ElasticEase;
  46909. }(EasingFunction));
  46910. BABYLON.ElasticEase = ElasticEase;
  46911. var ExponentialEase = /** @class */ (function (_super) {
  46912. __extends(ExponentialEase, _super);
  46913. function ExponentialEase(exponent) {
  46914. if (exponent === void 0) { exponent = 2; }
  46915. var _this = _super.call(this) || this;
  46916. _this.exponent = exponent;
  46917. return _this;
  46918. }
  46919. ExponentialEase.prototype.easeInCore = function (gradient) {
  46920. if (this.exponent <= 0) {
  46921. return gradient;
  46922. }
  46923. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  46924. };
  46925. return ExponentialEase;
  46926. }(EasingFunction));
  46927. BABYLON.ExponentialEase = ExponentialEase;
  46928. var PowerEase = /** @class */ (function (_super) {
  46929. __extends(PowerEase, _super);
  46930. function PowerEase(power) {
  46931. if (power === void 0) { power = 2; }
  46932. var _this = _super.call(this) || this;
  46933. _this.power = power;
  46934. return _this;
  46935. }
  46936. PowerEase.prototype.easeInCore = function (gradient) {
  46937. var y = Math.max(0.0, this.power);
  46938. return Math.pow(gradient, y);
  46939. };
  46940. return PowerEase;
  46941. }(EasingFunction));
  46942. BABYLON.PowerEase = PowerEase;
  46943. var QuadraticEase = /** @class */ (function (_super) {
  46944. __extends(QuadraticEase, _super);
  46945. function QuadraticEase() {
  46946. return _super !== null && _super.apply(this, arguments) || this;
  46947. }
  46948. QuadraticEase.prototype.easeInCore = function (gradient) {
  46949. return (gradient * gradient);
  46950. };
  46951. return QuadraticEase;
  46952. }(EasingFunction));
  46953. BABYLON.QuadraticEase = QuadraticEase;
  46954. var QuarticEase = /** @class */ (function (_super) {
  46955. __extends(QuarticEase, _super);
  46956. function QuarticEase() {
  46957. return _super !== null && _super.apply(this, arguments) || this;
  46958. }
  46959. QuarticEase.prototype.easeInCore = function (gradient) {
  46960. return (gradient * gradient * gradient * gradient);
  46961. };
  46962. return QuarticEase;
  46963. }(EasingFunction));
  46964. BABYLON.QuarticEase = QuarticEase;
  46965. var QuinticEase = /** @class */ (function (_super) {
  46966. __extends(QuinticEase, _super);
  46967. function QuinticEase() {
  46968. return _super !== null && _super.apply(this, arguments) || this;
  46969. }
  46970. QuinticEase.prototype.easeInCore = function (gradient) {
  46971. return (gradient * gradient * gradient * gradient * gradient);
  46972. };
  46973. return QuinticEase;
  46974. }(EasingFunction));
  46975. BABYLON.QuinticEase = QuinticEase;
  46976. var SineEase = /** @class */ (function (_super) {
  46977. __extends(SineEase, _super);
  46978. function SineEase() {
  46979. return _super !== null && _super.apply(this, arguments) || this;
  46980. }
  46981. SineEase.prototype.easeInCore = function (gradient) {
  46982. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  46983. };
  46984. return SineEase;
  46985. }(EasingFunction));
  46986. BABYLON.SineEase = SineEase;
  46987. var BezierCurveEase = /** @class */ (function (_super) {
  46988. __extends(BezierCurveEase, _super);
  46989. function BezierCurveEase(x1, y1, x2, y2) {
  46990. if (x1 === void 0) { x1 = 0; }
  46991. if (y1 === void 0) { y1 = 0; }
  46992. if (x2 === void 0) { x2 = 1; }
  46993. if (y2 === void 0) { y2 = 1; }
  46994. var _this = _super.call(this) || this;
  46995. _this.x1 = x1;
  46996. _this.y1 = y1;
  46997. _this.x2 = x2;
  46998. _this.y2 = y2;
  46999. return _this;
  47000. }
  47001. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47002. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47003. };
  47004. return BezierCurveEase;
  47005. }(EasingFunction));
  47006. BABYLON.BezierCurveEase = BezierCurveEase;
  47007. })(BABYLON || (BABYLON = {}));
  47008. //# sourceMappingURL=babylon.easing.js.map
  47009. var BABYLON;
  47010. (function (BABYLON) {
  47011. var Condition = /** @class */ (function () {
  47012. function Condition(actionManager) {
  47013. this._actionManager = actionManager;
  47014. }
  47015. Condition.prototype.isValid = function () {
  47016. return true;
  47017. };
  47018. Condition.prototype._getProperty = function (propertyPath) {
  47019. return this._actionManager._getProperty(propertyPath);
  47020. };
  47021. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47022. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47023. };
  47024. Condition.prototype.serialize = function () {
  47025. };
  47026. Condition.prototype._serialize = function (serializedCondition) {
  47027. return {
  47028. type: 2,
  47029. children: [],
  47030. name: serializedCondition.name,
  47031. properties: serializedCondition.properties
  47032. };
  47033. };
  47034. return Condition;
  47035. }());
  47036. BABYLON.Condition = Condition;
  47037. var ValueCondition = /** @class */ (function (_super) {
  47038. __extends(ValueCondition, _super);
  47039. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47040. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47041. var _this = _super.call(this, actionManager) || this;
  47042. _this.propertyPath = propertyPath;
  47043. _this.value = value;
  47044. _this.operator = operator;
  47045. _this._target = target;
  47046. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47047. _this._property = _this._getProperty(_this.propertyPath);
  47048. return _this;
  47049. }
  47050. Object.defineProperty(ValueCondition, "IsEqual", {
  47051. get: function () {
  47052. return ValueCondition._IsEqual;
  47053. },
  47054. enumerable: true,
  47055. configurable: true
  47056. });
  47057. Object.defineProperty(ValueCondition, "IsDifferent", {
  47058. get: function () {
  47059. return ValueCondition._IsDifferent;
  47060. },
  47061. enumerable: true,
  47062. configurable: true
  47063. });
  47064. Object.defineProperty(ValueCondition, "IsGreater", {
  47065. get: function () {
  47066. return ValueCondition._IsGreater;
  47067. },
  47068. enumerable: true,
  47069. configurable: true
  47070. });
  47071. Object.defineProperty(ValueCondition, "IsLesser", {
  47072. get: function () {
  47073. return ValueCondition._IsLesser;
  47074. },
  47075. enumerable: true,
  47076. configurable: true
  47077. });
  47078. // Methods
  47079. ValueCondition.prototype.isValid = function () {
  47080. switch (this.operator) {
  47081. case ValueCondition.IsGreater:
  47082. return this._effectiveTarget[this._property] > this.value;
  47083. case ValueCondition.IsLesser:
  47084. return this._effectiveTarget[this._property] < this.value;
  47085. case ValueCondition.IsEqual:
  47086. case ValueCondition.IsDifferent:
  47087. var check;
  47088. if (this.value.equals) {
  47089. check = this.value.equals(this._effectiveTarget[this._property]);
  47090. }
  47091. else {
  47092. check = this.value === this._effectiveTarget[this._property];
  47093. }
  47094. return this.operator === ValueCondition.IsEqual ? check : !check;
  47095. }
  47096. return false;
  47097. };
  47098. ValueCondition.prototype.serialize = function () {
  47099. return this._serialize({
  47100. name: "ValueCondition",
  47101. properties: [
  47102. BABYLON.Action._GetTargetProperty(this._target),
  47103. { name: "propertyPath", value: this.propertyPath },
  47104. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47105. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47106. ]
  47107. });
  47108. };
  47109. ValueCondition.GetOperatorName = function (operator) {
  47110. switch (operator) {
  47111. case ValueCondition._IsEqual: return "IsEqual";
  47112. case ValueCondition._IsDifferent: return "IsDifferent";
  47113. case ValueCondition._IsGreater: return "IsGreater";
  47114. case ValueCondition._IsLesser: return "IsLesser";
  47115. default: return "";
  47116. }
  47117. };
  47118. // Statics
  47119. ValueCondition._IsEqual = 0;
  47120. ValueCondition._IsDifferent = 1;
  47121. ValueCondition._IsGreater = 2;
  47122. ValueCondition._IsLesser = 3;
  47123. return ValueCondition;
  47124. }(Condition));
  47125. BABYLON.ValueCondition = ValueCondition;
  47126. var PredicateCondition = /** @class */ (function (_super) {
  47127. __extends(PredicateCondition, _super);
  47128. function PredicateCondition(actionManager, predicate) {
  47129. var _this = _super.call(this, actionManager) || this;
  47130. _this.predicate = predicate;
  47131. return _this;
  47132. }
  47133. PredicateCondition.prototype.isValid = function () {
  47134. return this.predicate();
  47135. };
  47136. return PredicateCondition;
  47137. }(Condition));
  47138. BABYLON.PredicateCondition = PredicateCondition;
  47139. var StateCondition = /** @class */ (function (_super) {
  47140. __extends(StateCondition, _super);
  47141. function StateCondition(actionManager, target, value) {
  47142. var _this = _super.call(this, actionManager) || this;
  47143. _this.value = value;
  47144. _this._target = target;
  47145. return _this;
  47146. }
  47147. // Methods
  47148. StateCondition.prototype.isValid = function () {
  47149. return this._target.state === this.value;
  47150. };
  47151. StateCondition.prototype.serialize = function () {
  47152. return this._serialize({
  47153. name: "StateCondition",
  47154. properties: [
  47155. BABYLON.Action._GetTargetProperty(this._target),
  47156. { name: "value", value: this.value }
  47157. ]
  47158. });
  47159. };
  47160. return StateCondition;
  47161. }(Condition));
  47162. BABYLON.StateCondition = StateCondition;
  47163. })(BABYLON || (BABYLON = {}));
  47164. //# sourceMappingURL=babylon.condition.js.map
  47165. var BABYLON;
  47166. (function (BABYLON) {
  47167. var Action = /** @class */ (function () {
  47168. function Action(triggerOptions, condition) {
  47169. this.triggerOptions = triggerOptions;
  47170. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47171. if (triggerOptions.parameter) {
  47172. this.trigger = triggerOptions.trigger;
  47173. this._triggerParameter = triggerOptions.parameter;
  47174. }
  47175. else {
  47176. this.trigger = triggerOptions;
  47177. }
  47178. this._nextActiveAction = this;
  47179. this._condition = condition;
  47180. }
  47181. // Methods
  47182. Action.prototype._prepare = function () {
  47183. };
  47184. Action.prototype.getTriggerParameter = function () {
  47185. return this._triggerParameter;
  47186. };
  47187. Action.prototype._executeCurrent = function (evt) {
  47188. if (this._nextActiveAction._condition) {
  47189. var condition = this._nextActiveAction._condition;
  47190. var currentRenderId = this._actionManager.getScene().getRenderId();
  47191. // We cache the current evaluation for the current frame
  47192. if (condition._evaluationId === currentRenderId) {
  47193. if (!condition._currentResult) {
  47194. return;
  47195. }
  47196. }
  47197. else {
  47198. condition._evaluationId = currentRenderId;
  47199. if (!condition.isValid()) {
  47200. condition._currentResult = false;
  47201. return;
  47202. }
  47203. condition._currentResult = true;
  47204. }
  47205. }
  47206. this.onBeforeExecuteObservable.notifyObservers(this);
  47207. this._nextActiveAction.execute(evt);
  47208. this.skipToNextActiveAction();
  47209. };
  47210. Action.prototype.execute = function (evt) {
  47211. };
  47212. Action.prototype.skipToNextActiveAction = function () {
  47213. if (this._nextActiveAction._child) {
  47214. if (!this._nextActiveAction._child._actionManager) {
  47215. this._nextActiveAction._child._actionManager = this._actionManager;
  47216. }
  47217. this._nextActiveAction = this._nextActiveAction._child;
  47218. }
  47219. else {
  47220. this._nextActiveAction = this;
  47221. }
  47222. };
  47223. Action.prototype.then = function (action) {
  47224. this._child = action;
  47225. action._actionManager = this._actionManager;
  47226. action._prepare();
  47227. return action;
  47228. };
  47229. Action.prototype._getProperty = function (propertyPath) {
  47230. return this._actionManager._getProperty(propertyPath);
  47231. };
  47232. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47233. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47234. };
  47235. Action.prototype.serialize = function (parent) {
  47236. };
  47237. // Called by BABYLON.Action objects in serialize(...). Internal use
  47238. Action.prototype._serialize = function (serializedAction, parent) {
  47239. var serializationObject = {
  47240. type: 1,
  47241. children: [],
  47242. name: serializedAction.name,
  47243. properties: serializedAction.properties || []
  47244. };
  47245. // Serialize child
  47246. if (this._child) {
  47247. this._child.serialize(serializationObject);
  47248. }
  47249. // Check if "this" has a condition
  47250. if (this._condition) {
  47251. var serializedCondition = this._condition.serialize();
  47252. serializedCondition.children.push(serializationObject);
  47253. if (parent) {
  47254. parent.children.push(serializedCondition);
  47255. }
  47256. return serializedCondition;
  47257. }
  47258. if (parent) {
  47259. parent.children.push(serializationObject);
  47260. }
  47261. return serializationObject;
  47262. };
  47263. Action._SerializeValueAsString = function (value) {
  47264. if (typeof value === "number") {
  47265. return value.toString();
  47266. }
  47267. if (typeof value === "boolean") {
  47268. return value ? "true" : "false";
  47269. }
  47270. if (value instanceof BABYLON.Vector2) {
  47271. return value.x + ", " + value.y;
  47272. }
  47273. if (value instanceof BABYLON.Vector3) {
  47274. return value.x + ", " + value.y + ", " + value.z;
  47275. }
  47276. if (value instanceof BABYLON.Color3) {
  47277. return value.r + ", " + value.g + ", " + value.b;
  47278. }
  47279. if (value instanceof BABYLON.Color4) {
  47280. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47281. }
  47282. return value; // string
  47283. };
  47284. Action._GetTargetProperty = function (target) {
  47285. return {
  47286. name: "target",
  47287. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47288. : target instanceof BABYLON.Light ? "LightProperties"
  47289. : target instanceof BABYLON.Camera ? "CameraProperties"
  47290. : "SceneProperties",
  47291. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47292. };
  47293. };
  47294. return Action;
  47295. }());
  47296. BABYLON.Action = Action;
  47297. })(BABYLON || (BABYLON = {}));
  47298. //# sourceMappingURL=babylon.action.js.map
  47299. var BABYLON;
  47300. (function (BABYLON) {
  47301. /**
  47302. * ActionEvent is the event beint sent when an action is triggered.
  47303. */
  47304. var ActionEvent = /** @class */ (function () {
  47305. /**
  47306. * @param source The mesh or sprite that triggered the action.
  47307. * @param pointerX The X mouse cursor position at the time of the event
  47308. * @param pointerY The Y mouse cursor position at the time of the event
  47309. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47310. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47311. */
  47312. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47313. this.source = source;
  47314. this.pointerX = pointerX;
  47315. this.pointerY = pointerY;
  47316. this.meshUnderPointer = meshUnderPointer;
  47317. this.sourceEvent = sourceEvent;
  47318. this.additionalData = additionalData;
  47319. }
  47320. /**
  47321. * Helper function to auto-create an ActionEvent from a source mesh.
  47322. * @param source The source mesh that triggered the event
  47323. * @param evt {Event} The original (browser) event
  47324. */
  47325. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47326. var scene = source.getScene();
  47327. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47328. };
  47329. /**
  47330. * Helper function to auto-create an ActionEvent from a source mesh.
  47331. * @param source The source sprite that triggered the event
  47332. * @param scene Scene associated with the sprite
  47333. * @param evt {Event} The original (browser) event
  47334. */
  47335. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47336. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47337. };
  47338. /**
  47339. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47340. * @param scene the scene where the event occurred
  47341. * @param evt {Event} The original (browser) event
  47342. */
  47343. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47344. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47345. };
  47346. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47347. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47348. };
  47349. return ActionEvent;
  47350. }());
  47351. BABYLON.ActionEvent = ActionEvent;
  47352. /**
  47353. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47354. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47355. */
  47356. var ActionManager = /** @class */ (function () {
  47357. function ActionManager(scene) {
  47358. // Members
  47359. this.actions = new Array();
  47360. this.hoverCursor = '';
  47361. this._scene = scene;
  47362. scene._actionManagers.push(this);
  47363. }
  47364. Object.defineProperty(ActionManager, "NothingTrigger", {
  47365. get: function () {
  47366. return ActionManager._NothingTrigger;
  47367. },
  47368. enumerable: true,
  47369. configurable: true
  47370. });
  47371. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47372. get: function () {
  47373. return ActionManager._OnPickTrigger;
  47374. },
  47375. enumerable: true,
  47376. configurable: true
  47377. });
  47378. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47379. get: function () {
  47380. return ActionManager._OnLeftPickTrigger;
  47381. },
  47382. enumerable: true,
  47383. configurable: true
  47384. });
  47385. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47386. get: function () {
  47387. return ActionManager._OnRightPickTrigger;
  47388. },
  47389. enumerable: true,
  47390. configurable: true
  47391. });
  47392. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47393. get: function () {
  47394. return ActionManager._OnCenterPickTrigger;
  47395. },
  47396. enumerable: true,
  47397. configurable: true
  47398. });
  47399. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47400. get: function () {
  47401. return ActionManager._OnPickDownTrigger;
  47402. },
  47403. enumerable: true,
  47404. configurable: true
  47405. });
  47406. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47407. get: function () {
  47408. return ActionManager._OnDoublePickTrigger;
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47414. get: function () {
  47415. return ActionManager._OnPickUpTrigger;
  47416. },
  47417. enumerable: true,
  47418. configurable: true
  47419. });
  47420. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47421. /// This trigger will only be raised if you also declared a OnPickDown
  47422. get: function () {
  47423. return ActionManager._OnPickOutTrigger;
  47424. },
  47425. enumerable: true,
  47426. configurable: true
  47427. });
  47428. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47429. get: function () {
  47430. return ActionManager._OnLongPressTrigger;
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47436. get: function () {
  47437. return ActionManager._OnPointerOverTrigger;
  47438. },
  47439. enumerable: true,
  47440. configurable: true
  47441. });
  47442. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47443. get: function () {
  47444. return ActionManager._OnPointerOutTrigger;
  47445. },
  47446. enumerable: true,
  47447. configurable: true
  47448. });
  47449. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47450. get: function () {
  47451. return ActionManager._OnEveryFrameTrigger;
  47452. },
  47453. enumerable: true,
  47454. configurable: true
  47455. });
  47456. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47457. get: function () {
  47458. return ActionManager._OnIntersectionEnterTrigger;
  47459. },
  47460. enumerable: true,
  47461. configurable: true
  47462. });
  47463. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47464. get: function () {
  47465. return ActionManager._OnIntersectionExitTrigger;
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47471. get: function () {
  47472. return ActionManager._OnKeyDownTrigger;
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47478. get: function () {
  47479. return ActionManager._OnKeyUpTrigger;
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. // Methods
  47485. ActionManager.prototype.dispose = function () {
  47486. var index = this._scene._actionManagers.indexOf(this);
  47487. for (var i = 0; i < this.actions.length; i++) {
  47488. var action = this.actions[i];
  47489. ActionManager.Triggers[action.trigger]--;
  47490. if (ActionManager.Triggers[action.trigger] === 0) {
  47491. delete ActionManager.Triggers[action.trigger];
  47492. }
  47493. }
  47494. if (index > -1) {
  47495. this._scene._actionManagers.splice(index, 1);
  47496. }
  47497. };
  47498. ActionManager.prototype.getScene = function () {
  47499. return this._scene;
  47500. };
  47501. /**
  47502. * Does this action manager handles actions of any of the given triggers
  47503. * @param {number[]} triggers - the triggers to be tested
  47504. * @return {boolean} whether one (or more) of the triggers is handeled
  47505. */
  47506. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47507. for (var index = 0; index < this.actions.length; index++) {
  47508. var action = this.actions[index];
  47509. if (triggers.indexOf(action.trigger) > -1) {
  47510. return true;
  47511. }
  47512. }
  47513. return false;
  47514. };
  47515. /**
  47516. * Does this action manager handles actions of a given trigger
  47517. * @param {number} trigger - the trigger to be tested
  47518. * @return {boolean} whether the trigger is handeled
  47519. */
  47520. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47521. for (var index = 0; index < this.actions.length; index++) {
  47522. var action = this.actions[index];
  47523. if (action.trigger === trigger) {
  47524. return true;
  47525. }
  47526. }
  47527. return false;
  47528. };
  47529. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47530. /**
  47531. * Does this action manager has pointer triggers
  47532. * @return {boolean} whether or not it has pointer triggers
  47533. */
  47534. get: function () {
  47535. for (var index = 0; index < this.actions.length; index++) {
  47536. var action = this.actions[index];
  47537. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47538. return true;
  47539. }
  47540. }
  47541. return false;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47547. /**
  47548. * Does this action manager has pick triggers
  47549. * @return {boolean} whether or not it has pick triggers
  47550. */
  47551. get: function () {
  47552. for (var index = 0; index < this.actions.length; index++) {
  47553. var action = this.actions[index];
  47554. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47555. return true;
  47556. }
  47557. }
  47558. return false;
  47559. },
  47560. enumerable: true,
  47561. configurable: true
  47562. });
  47563. Object.defineProperty(ActionManager, "HasTriggers", {
  47564. /**
  47565. * Does exist one action manager with at least one trigger
  47566. * @return {boolean} whether or not it exists one action manager with one trigger
  47567. **/
  47568. get: function () {
  47569. for (var t in ActionManager.Triggers) {
  47570. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47571. return true;
  47572. }
  47573. }
  47574. return false;
  47575. },
  47576. enumerable: true,
  47577. configurable: true
  47578. });
  47579. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47580. /**
  47581. * Does exist one action manager with at least one pick trigger
  47582. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47583. **/
  47584. get: function () {
  47585. for (var t in ActionManager.Triggers) {
  47586. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47587. var t_int = parseInt(t);
  47588. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47589. return true;
  47590. }
  47591. }
  47592. }
  47593. return false;
  47594. },
  47595. enumerable: true,
  47596. configurable: true
  47597. });
  47598. /**
  47599. * Does exist one action manager that handles actions of a given trigger
  47600. * @param {number} trigger - the trigger to be tested
  47601. * @return {boolean} whether the trigger is handeled by at least one action manager
  47602. **/
  47603. ActionManager.HasSpecificTrigger = function (trigger) {
  47604. for (var t in ActionManager.Triggers) {
  47605. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47606. var t_int = parseInt(t);
  47607. if (t_int === trigger) {
  47608. return true;
  47609. }
  47610. }
  47611. }
  47612. return false;
  47613. };
  47614. /**
  47615. * Registers an action to this action manager
  47616. * @param {BABYLON.Action} action - the action to be registered
  47617. * @return {BABYLON.Action} the action amended (prepared) after registration
  47618. */
  47619. ActionManager.prototype.registerAction = function (action) {
  47620. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47621. if (this.getScene().actionManager !== this) {
  47622. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47623. return null;
  47624. }
  47625. }
  47626. this.actions.push(action);
  47627. if (ActionManager.Triggers[action.trigger]) {
  47628. ActionManager.Triggers[action.trigger]++;
  47629. }
  47630. else {
  47631. ActionManager.Triggers[action.trigger] = 1;
  47632. }
  47633. action._actionManager = this;
  47634. action._prepare();
  47635. return action;
  47636. };
  47637. /**
  47638. * Unregisters an action to this action manager
  47639. * @param action The action to be unregistered
  47640. * @return whether the action has been unregistered
  47641. */
  47642. ActionManager.prototype.unregisterAction = function (action) {
  47643. var index = this.actions.indexOf(action);
  47644. if (index !== -1) {
  47645. this.actions.splice(index, 1);
  47646. ActionManager.Triggers[action.trigger] -= 1;
  47647. if (ActionManager.Triggers[action.trigger] === 0) {
  47648. delete ActionManager.Triggers[action.trigger];
  47649. }
  47650. delete action._actionManager;
  47651. return true;
  47652. }
  47653. return false;
  47654. };
  47655. /**
  47656. * Process a specific trigger
  47657. * @param {number} trigger - the trigger to process
  47658. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47659. */
  47660. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47661. for (var index = 0; index < this.actions.length; index++) {
  47662. var action = this.actions[index];
  47663. if (action.trigger === trigger) {
  47664. if (evt) {
  47665. if (trigger === ActionManager.OnKeyUpTrigger
  47666. || trigger === ActionManager.OnKeyDownTrigger) {
  47667. var parameter = action.getTriggerParameter();
  47668. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47669. if (!parameter.toLowerCase) {
  47670. continue;
  47671. }
  47672. var lowerCase = parameter.toLowerCase();
  47673. if (lowerCase !== evt.sourceEvent.key) {
  47674. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47675. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47676. if (actualkey !== lowerCase) {
  47677. continue;
  47678. }
  47679. }
  47680. }
  47681. }
  47682. }
  47683. action._executeCurrent(evt);
  47684. }
  47685. }
  47686. };
  47687. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47688. var properties = propertyPath.split(".");
  47689. for (var index = 0; index < properties.length - 1; index++) {
  47690. target = target[properties[index]];
  47691. }
  47692. return target;
  47693. };
  47694. ActionManager.prototype._getProperty = function (propertyPath) {
  47695. var properties = propertyPath.split(".");
  47696. return properties[properties.length - 1];
  47697. };
  47698. ActionManager.prototype.serialize = function (name) {
  47699. var root = {
  47700. children: new Array(),
  47701. name: name,
  47702. type: 3,
  47703. properties: new Array() // Empty for root but required
  47704. };
  47705. for (var i = 0; i < this.actions.length; i++) {
  47706. var triggerObject = {
  47707. type: 0,
  47708. children: new Array(),
  47709. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47710. properties: new Array()
  47711. };
  47712. var triggerOptions = this.actions[i].triggerOptions;
  47713. if (triggerOptions && typeof triggerOptions !== "number") {
  47714. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47715. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47716. }
  47717. else {
  47718. var parameter = {};
  47719. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47720. if (triggerOptions.parameter.mesh) {
  47721. parameter._meshId = triggerOptions.parameter.mesh.id;
  47722. }
  47723. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47724. }
  47725. }
  47726. // Serialize child action, recursively
  47727. this.actions[i].serialize(triggerObject);
  47728. // Add serialized trigger
  47729. root.children.push(triggerObject);
  47730. }
  47731. return root;
  47732. };
  47733. ActionManager.Parse = function (parsedActions, object, scene) {
  47734. var actionManager = new ActionManager(scene);
  47735. if (object === null)
  47736. scene.actionManager = actionManager;
  47737. else
  47738. object.actionManager = actionManager;
  47739. // instanciate a new object
  47740. var instanciate = function (name, params) {
  47741. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47742. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47743. newInstance.constructor.apply(newInstance, params);
  47744. return newInstance;
  47745. };
  47746. var parseParameter = function (name, value, target, propertyPath) {
  47747. if (propertyPath === null) {
  47748. // String, boolean or float
  47749. var floatValue = parseFloat(value);
  47750. if (value === "true" || value === "false")
  47751. return value === "true";
  47752. else
  47753. return isNaN(floatValue) ? value : floatValue;
  47754. }
  47755. var effectiveTarget = propertyPath.split(".");
  47756. var values = value.split(",");
  47757. // Get effective Target
  47758. for (var i = 0; i < effectiveTarget.length; i++) {
  47759. target = target[effectiveTarget[i]];
  47760. }
  47761. // Return appropriate value with its type
  47762. if (typeof (target) === "boolean")
  47763. return values[0] === "true";
  47764. if (typeof (target) === "string")
  47765. return values[0];
  47766. // Parameters with multiple values such as Vector3 etc.
  47767. var split = new Array();
  47768. for (var i = 0; i < values.length; i++)
  47769. split.push(parseFloat(values[i]));
  47770. if (target instanceof BABYLON.Vector3)
  47771. return BABYLON.Vector3.FromArray(split);
  47772. if (target instanceof BABYLON.Vector4)
  47773. return BABYLON.Vector4.FromArray(split);
  47774. if (target instanceof BABYLON.Color3)
  47775. return BABYLON.Color3.FromArray(split);
  47776. if (target instanceof BABYLON.Color4)
  47777. return BABYLON.Color4.FromArray(split);
  47778. return parseFloat(values[0]);
  47779. };
  47780. // traverse graph per trigger
  47781. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47782. if (combineArray === void 0) { combineArray = null; }
  47783. if (parsedAction.detached)
  47784. return;
  47785. var parameters = new Array();
  47786. var target = null;
  47787. var propertyPath = null;
  47788. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47789. // Parameters
  47790. if (parsedAction.type === 2)
  47791. parameters.push(actionManager);
  47792. else
  47793. parameters.push(trigger);
  47794. if (combine) {
  47795. var actions = new Array();
  47796. for (var j = 0; j < parsedAction.combine.length; j++) {
  47797. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47798. }
  47799. parameters.push(actions);
  47800. }
  47801. else {
  47802. for (var i = 0; i < parsedAction.properties.length; i++) {
  47803. var value = parsedAction.properties[i].value;
  47804. var name = parsedAction.properties[i].name;
  47805. var targetType = parsedAction.properties[i].targetType;
  47806. if (name === "target")
  47807. if (targetType !== null && targetType === "SceneProperties")
  47808. value = target = scene;
  47809. else
  47810. value = target = scene.getNodeByName(value);
  47811. else if (name === "parent")
  47812. value = scene.getNodeByName(value);
  47813. else if (name === "sound")
  47814. value = scene.getSoundByName(value);
  47815. else if (name !== "propertyPath") {
  47816. if (parsedAction.type === 2 && name === "operator")
  47817. value = BABYLON.ValueCondition[value];
  47818. else
  47819. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47820. }
  47821. else {
  47822. propertyPath = value;
  47823. }
  47824. parameters.push(value);
  47825. }
  47826. }
  47827. if (combineArray === null) {
  47828. parameters.push(condition);
  47829. }
  47830. else {
  47831. parameters.push(null);
  47832. }
  47833. // If interpolate value action
  47834. if (parsedAction.name === "InterpolateValueAction") {
  47835. var param = parameters[parameters.length - 2];
  47836. parameters[parameters.length - 1] = param;
  47837. parameters[parameters.length - 2] = condition;
  47838. }
  47839. // Action or condition(s) and not CombineAction
  47840. var newAction = instanciate(parsedAction.name, parameters);
  47841. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47842. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47843. if (action)
  47844. action.then(nothing);
  47845. else
  47846. actionManager.registerAction(nothing);
  47847. action = nothing;
  47848. }
  47849. if (combineArray === null) {
  47850. if (newAction instanceof BABYLON.Condition) {
  47851. condition = newAction;
  47852. newAction = action;
  47853. }
  47854. else {
  47855. condition = null;
  47856. if (action)
  47857. action.then(newAction);
  47858. else
  47859. actionManager.registerAction(newAction);
  47860. }
  47861. }
  47862. else {
  47863. combineArray.push(newAction);
  47864. }
  47865. for (var i = 0; i < parsedAction.children.length; i++)
  47866. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47867. };
  47868. // triggers
  47869. for (var i = 0; i < parsedActions.children.length; i++) {
  47870. var triggerParams;
  47871. var trigger = parsedActions.children[i];
  47872. if (trigger.properties.length > 0) {
  47873. var param = trigger.properties[0].value;
  47874. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47875. if (value._meshId) {
  47876. value.mesh = scene.getMeshByID(value._meshId);
  47877. }
  47878. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47879. }
  47880. else
  47881. triggerParams = ActionManager[trigger.name];
  47882. for (var j = 0; j < trigger.children.length; j++) {
  47883. if (!trigger.detached)
  47884. traverse(trigger.children[j], triggerParams, null, null);
  47885. }
  47886. }
  47887. };
  47888. ActionManager.GetTriggerName = function (trigger) {
  47889. switch (trigger) {
  47890. case 0: return "NothingTrigger";
  47891. case 1: return "OnPickTrigger";
  47892. case 2: return "OnLeftPickTrigger";
  47893. case 3: return "OnRightPickTrigger";
  47894. case 4: return "OnCenterPickTrigger";
  47895. case 5: return "OnPickDownTrigger";
  47896. case 6: return "OnPickUpTrigger";
  47897. case 7: return "OnLongPressTrigger";
  47898. case 8: return "OnPointerOverTrigger";
  47899. case 9: return "OnPointerOutTrigger";
  47900. case 10: return "OnEveryFrameTrigger";
  47901. case 11: return "OnIntersectionEnterTrigger";
  47902. case 12: return "OnIntersectionExitTrigger";
  47903. case 13: return "OnKeyDownTrigger";
  47904. case 14: return "OnKeyUpTrigger";
  47905. case 15: return "OnPickOutTrigger";
  47906. default: return "";
  47907. }
  47908. };
  47909. // Statics
  47910. ActionManager._NothingTrigger = 0;
  47911. ActionManager._OnPickTrigger = 1;
  47912. ActionManager._OnLeftPickTrigger = 2;
  47913. ActionManager._OnRightPickTrigger = 3;
  47914. ActionManager._OnCenterPickTrigger = 4;
  47915. ActionManager._OnPickDownTrigger = 5;
  47916. ActionManager._OnDoublePickTrigger = 6;
  47917. ActionManager._OnPickUpTrigger = 7;
  47918. ActionManager._OnLongPressTrigger = 8;
  47919. ActionManager._OnPointerOverTrigger = 9;
  47920. ActionManager._OnPointerOutTrigger = 10;
  47921. ActionManager._OnEveryFrameTrigger = 11;
  47922. ActionManager._OnIntersectionEnterTrigger = 12;
  47923. ActionManager._OnIntersectionExitTrigger = 13;
  47924. ActionManager._OnKeyDownTrigger = 14;
  47925. ActionManager._OnKeyUpTrigger = 15;
  47926. ActionManager._OnPickOutTrigger = 16;
  47927. ActionManager.Triggers = {};
  47928. return ActionManager;
  47929. }());
  47930. BABYLON.ActionManager = ActionManager;
  47931. })(BABYLON || (BABYLON = {}));
  47932. //# sourceMappingURL=babylon.actionManager.js.map
  47933. var BABYLON;
  47934. (function (BABYLON) {
  47935. var InterpolateValueAction = /** @class */ (function (_super) {
  47936. __extends(InterpolateValueAction, _super);
  47937. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  47938. if (duration === void 0) { duration = 1000; }
  47939. var _this = _super.call(this, triggerOptions, condition) || this;
  47940. _this.propertyPath = propertyPath;
  47941. _this.value = value;
  47942. _this.duration = duration;
  47943. _this.stopOtherAnimations = stopOtherAnimations;
  47944. _this.onInterpolationDone = onInterpolationDone;
  47945. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  47946. _this._target = _this._effectiveTarget = target;
  47947. return _this;
  47948. }
  47949. InterpolateValueAction.prototype._prepare = function () {
  47950. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47951. this._property = this._getProperty(this.propertyPath);
  47952. };
  47953. InterpolateValueAction.prototype.execute = function () {
  47954. var _this = this;
  47955. var scene = this._actionManager.getScene();
  47956. var keys = [
  47957. {
  47958. frame: 0,
  47959. value: this._effectiveTarget[this._property]
  47960. }, {
  47961. frame: 100,
  47962. value: this.value
  47963. }
  47964. ];
  47965. var dataType;
  47966. if (typeof this.value === "number") {
  47967. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  47968. }
  47969. else if (this.value instanceof BABYLON.Color3) {
  47970. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  47971. }
  47972. else if (this.value instanceof BABYLON.Vector3) {
  47973. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  47974. }
  47975. else if (this.value instanceof BABYLON.Matrix) {
  47976. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  47977. }
  47978. else if (this.value instanceof BABYLON.Quaternion) {
  47979. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47980. }
  47981. else {
  47982. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47983. return;
  47984. }
  47985. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47986. animation.setKeys(keys);
  47987. if (this.stopOtherAnimations) {
  47988. scene.stopAnimation(this._effectiveTarget);
  47989. }
  47990. var wrapper = function () {
  47991. _this.onInterpolationDoneObservable.notifyObservers(_this);
  47992. if (_this.onInterpolationDone) {
  47993. _this.onInterpolationDone();
  47994. }
  47995. };
  47996. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  47997. };
  47998. InterpolateValueAction.prototype.serialize = function (parent) {
  47999. return _super.prototype._serialize.call(this, {
  48000. name: "InterpolateValueAction",
  48001. properties: [
  48002. BABYLON.Action._GetTargetProperty(this._target),
  48003. { name: "propertyPath", value: this.propertyPath },
  48004. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48005. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48006. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48007. ]
  48008. }, parent);
  48009. };
  48010. return InterpolateValueAction;
  48011. }(BABYLON.Action));
  48012. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48013. })(BABYLON || (BABYLON = {}));
  48014. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48015. var BABYLON;
  48016. (function (BABYLON) {
  48017. var SwitchBooleanAction = /** @class */ (function (_super) {
  48018. __extends(SwitchBooleanAction, _super);
  48019. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48020. var _this = _super.call(this, triggerOptions, condition) || this;
  48021. _this.propertyPath = propertyPath;
  48022. _this._target = _this._effectiveTarget = target;
  48023. return _this;
  48024. }
  48025. SwitchBooleanAction.prototype._prepare = function () {
  48026. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48027. this._property = this._getProperty(this.propertyPath);
  48028. };
  48029. SwitchBooleanAction.prototype.execute = function () {
  48030. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48031. };
  48032. SwitchBooleanAction.prototype.serialize = function (parent) {
  48033. return _super.prototype._serialize.call(this, {
  48034. name: "SwitchBooleanAction",
  48035. properties: [
  48036. BABYLON.Action._GetTargetProperty(this._target),
  48037. { name: "propertyPath", value: this.propertyPath }
  48038. ]
  48039. }, parent);
  48040. };
  48041. return SwitchBooleanAction;
  48042. }(BABYLON.Action));
  48043. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48044. var SetStateAction = /** @class */ (function (_super) {
  48045. __extends(SetStateAction, _super);
  48046. function SetStateAction(triggerOptions, target, value, condition) {
  48047. var _this = _super.call(this, triggerOptions, condition) || this;
  48048. _this.value = value;
  48049. _this._target = target;
  48050. return _this;
  48051. }
  48052. SetStateAction.prototype.execute = function () {
  48053. this._target.state = this.value;
  48054. };
  48055. SetStateAction.prototype.serialize = function (parent) {
  48056. return _super.prototype._serialize.call(this, {
  48057. name: "SetStateAction",
  48058. properties: [
  48059. BABYLON.Action._GetTargetProperty(this._target),
  48060. { name: "value", value: this.value }
  48061. ]
  48062. }, parent);
  48063. };
  48064. return SetStateAction;
  48065. }(BABYLON.Action));
  48066. BABYLON.SetStateAction = SetStateAction;
  48067. var SetValueAction = /** @class */ (function (_super) {
  48068. __extends(SetValueAction, _super);
  48069. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48070. var _this = _super.call(this, triggerOptions, condition) || this;
  48071. _this.propertyPath = propertyPath;
  48072. _this.value = value;
  48073. _this._target = _this._effectiveTarget = target;
  48074. return _this;
  48075. }
  48076. SetValueAction.prototype._prepare = function () {
  48077. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48078. this._property = this._getProperty(this.propertyPath);
  48079. };
  48080. SetValueAction.prototype.execute = function () {
  48081. this._effectiveTarget[this._property] = this.value;
  48082. if (this._target.markAsDirty) {
  48083. this._target.markAsDirty(this._property);
  48084. }
  48085. };
  48086. SetValueAction.prototype.serialize = function (parent) {
  48087. return _super.prototype._serialize.call(this, {
  48088. name: "SetValueAction",
  48089. properties: [
  48090. BABYLON.Action._GetTargetProperty(this._target),
  48091. { name: "propertyPath", value: this.propertyPath },
  48092. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48093. ]
  48094. }, parent);
  48095. };
  48096. return SetValueAction;
  48097. }(BABYLON.Action));
  48098. BABYLON.SetValueAction = SetValueAction;
  48099. var IncrementValueAction = /** @class */ (function (_super) {
  48100. __extends(IncrementValueAction, _super);
  48101. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48102. var _this = _super.call(this, triggerOptions, condition) || this;
  48103. _this.propertyPath = propertyPath;
  48104. _this.value = value;
  48105. _this._target = _this._effectiveTarget = target;
  48106. return _this;
  48107. }
  48108. IncrementValueAction.prototype._prepare = function () {
  48109. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48110. this._property = this._getProperty(this.propertyPath);
  48111. if (typeof this._effectiveTarget[this._property] !== "number") {
  48112. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48113. }
  48114. };
  48115. IncrementValueAction.prototype.execute = function () {
  48116. this._effectiveTarget[this._property] += this.value;
  48117. if (this._target.markAsDirty) {
  48118. this._target.markAsDirty(this._property);
  48119. }
  48120. };
  48121. IncrementValueAction.prototype.serialize = function (parent) {
  48122. return _super.prototype._serialize.call(this, {
  48123. name: "IncrementValueAction",
  48124. properties: [
  48125. BABYLON.Action._GetTargetProperty(this._target),
  48126. { name: "propertyPath", value: this.propertyPath },
  48127. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48128. ]
  48129. }, parent);
  48130. };
  48131. return IncrementValueAction;
  48132. }(BABYLON.Action));
  48133. BABYLON.IncrementValueAction = IncrementValueAction;
  48134. var PlayAnimationAction = /** @class */ (function (_super) {
  48135. __extends(PlayAnimationAction, _super);
  48136. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48137. var _this = _super.call(this, triggerOptions, condition) || this;
  48138. _this.from = from;
  48139. _this.to = to;
  48140. _this.loop = loop;
  48141. _this._target = target;
  48142. return _this;
  48143. }
  48144. PlayAnimationAction.prototype._prepare = function () {
  48145. };
  48146. PlayAnimationAction.prototype.execute = function () {
  48147. var scene = this._actionManager.getScene();
  48148. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48149. };
  48150. PlayAnimationAction.prototype.serialize = function (parent) {
  48151. return _super.prototype._serialize.call(this, {
  48152. name: "PlayAnimationAction",
  48153. properties: [
  48154. BABYLON.Action._GetTargetProperty(this._target),
  48155. { name: "from", value: String(this.from) },
  48156. { name: "to", value: String(this.to) },
  48157. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48158. ]
  48159. }, parent);
  48160. };
  48161. return PlayAnimationAction;
  48162. }(BABYLON.Action));
  48163. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48164. var StopAnimationAction = /** @class */ (function (_super) {
  48165. __extends(StopAnimationAction, _super);
  48166. function StopAnimationAction(triggerOptions, target, condition) {
  48167. var _this = _super.call(this, triggerOptions, condition) || this;
  48168. _this._target = target;
  48169. return _this;
  48170. }
  48171. StopAnimationAction.prototype._prepare = function () {
  48172. };
  48173. StopAnimationAction.prototype.execute = function () {
  48174. var scene = this._actionManager.getScene();
  48175. scene.stopAnimation(this._target);
  48176. };
  48177. StopAnimationAction.prototype.serialize = function (parent) {
  48178. return _super.prototype._serialize.call(this, {
  48179. name: "StopAnimationAction",
  48180. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48181. }, parent);
  48182. };
  48183. return StopAnimationAction;
  48184. }(BABYLON.Action));
  48185. BABYLON.StopAnimationAction = StopAnimationAction;
  48186. var DoNothingAction = /** @class */ (function (_super) {
  48187. __extends(DoNothingAction, _super);
  48188. function DoNothingAction(triggerOptions, condition) {
  48189. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48190. return _super.call(this, triggerOptions, condition) || this;
  48191. }
  48192. DoNothingAction.prototype.execute = function () {
  48193. };
  48194. DoNothingAction.prototype.serialize = function (parent) {
  48195. return _super.prototype._serialize.call(this, {
  48196. name: "DoNothingAction",
  48197. properties: []
  48198. }, parent);
  48199. };
  48200. return DoNothingAction;
  48201. }(BABYLON.Action));
  48202. BABYLON.DoNothingAction = DoNothingAction;
  48203. var CombineAction = /** @class */ (function (_super) {
  48204. __extends(CombineAction, _super);
  48205. function CombineAction(triggerOptions, children, condition) {
  48206. var _this = _super.call(this, triggerOptions, condition) || this;
  48207. _this.children = children;
  48208. return _this;
  48209. }
  48210. CombineAction.prototype._prepare = function () {
  48211. for (var index = 0; index < this.children.length; index++) {
  48212. this.children[index]._actionManager = this._actionManager;
  48213. this.children[index]._prepare();
  48214. }
  48215. };
  48216. CombineAction.prototype.execute = function (evt) {
  48217. for (var index = 0; index < this.children.length; index++) {
  48218. this.children[index].execute(evt);
  48219. }
  48220. };
  48221. CombineAction.prototype.serialize = function (parent) {
  48222. var serializationObject = _super.prototype._serialize.call(this, {
  48223. name: "CombineAction",
  48224. properties: [],
  48225. combine: []
  48226. }, parent);
  48227. for (var i = 0; i < this.children.length; i++) {
  48228. serializationObject.combine.push(this.children[i].serialize(null));
  48229. }
  48230. return serializationObject;
  48231. };
  48232. return CombineAction;
  48233. }(BABYLON.Action));
  48234. BABYLON.CombineAction = CombineAction;
  48235. var ExecuteCodeAction = /** @class */ (function (_super) {
  48236. __extends(ExecuteCodeAction, _super);
  48237. function ExecuteCodeAction(triggerOptions, func, condition) {
  48238. var _this = _super.call(this, triggerOptions, condition) || this;
  48239. _this.func = func;
  48240. return _this;
  48241. }
  48242. ExecuteCodeAction.prototype.execute = function (evt) {
  48243. this.func(evt);
  48244. };
  48245. return ExecuteCodeAction;
  48246. }(BABYLON.Action));
  48247. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48248. var SetParentAction = /** @class */ (function (_super) {
  48249. __extends(SetParentAction, _super);
  48250. function SetParentAction(triggerOptions, target, parent, condition) {
  48251. var _this = _super.call(this, triggerOptions, condition) || this;
  48252. _this._target = target;
  48253. _this._parent = parent;
  48254. return _this;
  48255. }
  48256. SetParentAction.prototype._prepare = function () {
  48257. };
  48258. SetParentAction.prototype.execute = function () {
  48259. if (this._target.parent === this._parent) {
  48260. return;
  48261. }
  48262. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48263. invertParentWorldMatrix.invert();
  48264. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48265. this._target.parent = this._parent;
  48266. };
  48267. SetParentAction.prototype.serialize = function (parent) {
  48268. return _super.prototype._serialize.call(this, {
  48269. name: "SetParentAction",
  48270. properties: [
  48271. BABYLON.Action._GetTargetProperty(this._target),
  48272. BABYLON.Action._GetTargetProperty(this._parent),
  48273. ]
  48274. }, parent);
  48275. };
  48276. return SetParentAction;
  48277. }(BABYLON.Action));
  48278. BABYLON.SetParentAction = SetParentAction;
  48279. var PlaySoundAction = /** @class */ (function (_super) {
  48280. __extends(PlaySoundAction, _super);
  48281. function PlaySoundAction(triggerOptions, sound, condition) {
  48282. var _this = _super.call(this, triggerOptions, condition) || this;
  48283. _this._sound = sound;
  48284. return _this;
  48285. }
  48286. PlaySoundAction.prototype._prepare = function () {
  48287. };
  48288. PlaySoundAction.prototype.execute = function () {
  48289. if (this._sound !== undefined)
  48290. this._sound.play();
  48291. };
  48292. PlaySoundAction.prototype.serialize = function (parent) {
  48293. return _super.prototype._serialize.call(this, {
  48294. name: "PlaySoundAction",
  48295. properties: [{ name: "sound", value: this._sound.name }]
  48296. }, parent);
  48297. };
  48298. return PlaySoundAction;
  48299. }(BABYLON.Action));
  48300. BABYLON.PlaySoundAction = PlaySoundAction;
  48301. var StopSoundAction = /** @class */ (function (_super) {
  48302. __extends(StopSoundAction, _super);
  48303. function StopSoundAction(triggerOptions, sound, condition) {
  48304. var _this = _super.call(this, triggerOptions, condition) || this;
  48305. _this._sound = sound;
  48306. return _this;
  48307. }
  48308. StopSoundAction.prototype._prepare = function () {
  48309. };
  48310. StopSoundAction.prototype.execute = function () {
  48311. if (this._sound !== undefined)
  48312. this._sound.stop();
  48313. };
  48314. StopSoundAction.prototype.serialize = function (parent) {
  48315. return _super.prototype._serialize.call(this, {
  48316. name: "StopSoundAction",
  48317. properties: [{ name: "sound", value: this._sound.name }]
  48318. }, parent);
  48319. };
  48320. return StopSoundAction;
  48321. }(BABYLON.Action));
  48322. BABYLON.StopSoundAction = StopSoundAction;
  48323. })(BABYLON || (BABYLON = {}));
  48324. //# sourceMappingURL=babylon.directActions.js.map
  48325. var BABYLON;
  48326. (function (BABYLON) {
  48327. var SpriteManager = /** @class */ (function () {
  48328. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48329. if (epsilon === void 0) { epsilon = 0.01; }
  48330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48331. this.name = name;
  48332. this.sprites = new Array();
  48333. this.renderingGroupId = 0;
  48334. this.layerMask = 0x0FFFFFFF;
  48335. this.fogEnabled = true;
  48336. this.isPickable = false;
  48337. /**
  48338. * An event triggered when the manager is disposed.
  48339. * @type {BABYLON.Observable}
  48340. */
  48341. this.onDisposeObservable = new BABYLON.Observable();
  48342. this._vertexBuffers = {};
  48343. this._capacity = capacity;
  48344. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48345. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48346. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48347. if (cellSize.width && cellSize.height) {
  48348. this.cellWidth = cellSize.width;
  48349. this.cellHeight = cellSize.height;
  48350. }
  48351. else if (cellSize !== undefined) {
  48352. this.cellWidth = cellSize;
  48353. this.cellHeight = cellSize;
  48354. }
  48355. else {
  48356. return;
  48357. }
  48358. this._epsilon = epsilon;
  48359. this._scene = scene;
  48360. this._scene.spriteManagers.push(this);
  48361. var indices = [];
  48362. var index = 0;
  48363. for (var count = 0; count < capacity; count++) {
  48364. indices.push(index);
  48365. indices.push(index + 1);
  48366. indices.push(index + 2);
  48367. indices.push(index);
  48368. indices.push(index + 2);
  48369. indices.push(index + 3);
  48370. index += 4;
  48371. }
  48372. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48373. // VBO
  48374. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48375. this._vertexData = new Float32Array(capacity * 16 * 4);
  48376. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48377. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48378. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48379. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48380. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48382. this._vertexBuffers["options"] = options;
  48383. this._vertexBuffers["cellInfo"] = cellInfo;
  48384. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48385. // Effects
  48386. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48387. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48388. }
  48389. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48390. set: function (callback) {
  48391. if (this._onDisposeObserver) {
  48392. this.onDisposeObservable.remove(this._onDisposeObserver);
  48393. }
  48394. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48395. },
  48396. enumerable: true,
  48397. configurable: true
  48398. });
  48399. Object.defineProperty(SpriteManager.prototype, "texture", {
  48400. get: function () {
  48401. return this._spriteTexture;
  48402. },
  48403. set: function (value) {
  48404. this._spriteTexture = value;
  48405. },
  48406. enumerable: true,
  48407. configurable: true
  48408. });
  48409. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48410. var arrayOffset = index * 16;
  48411. if (offsetX === 0)
  48412. offsetX = this._epsilon;
  48413. else if (offsetX === 1)
  48414. offsetX = 1 - this._epsilon;
  48415. if (offsetY === 0)
  48416. offsetY = this._epsilon;
  48417. else if (offsetY === 1)
  48418. offsetY = 1 - this._epsilon;
  48419. this._vertexData[arrayOffset] = sprite.position.x;
  48420. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48421. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48422. this._vertexData[arrayOffset + 3] = sprite.angle;
  48423. this._vertexData[arrayOffset + 4] = sprite.width;
  48424. this._vertexData[arrayOffset + 5] = sprite.height;
  48425. this._vertexData[arrayOffset + 6] = offsetX;
  48426. this._vertexData[arrayOffset + 7] = offsetY;
  48427. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48428. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48429. var offset = (sprite.cellIndex / rowSize) >> 0;
  48430. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48431. this._vertexData[arrayOffset + 11] = offset;
  48432. // Color
  48433. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48434. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48435. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48436. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48437. };
  48438. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48439. var count = Math.min(this._capacity, this.sprites.length);
  48440. var min = BABYLON.Vector3.Zero();
  48441. var max = BABYLON.Vector3.Zero();
  48442. var distance = Number.MAX_VALUE;
  48443. var currentSprite = null;
  48444. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48445. var cameraView = camera.getViewMatrix();
  48446. for (var index = 0; index < count; index++) {
  48447. var sprite = this.sprites[index];
  48448. if (!sprite) {
  48449. continue;
  48450. }
  48451. if (predicate) {
  48452. if (!predicate(sprite)) {
  48453. continue;
  48454. }
  48455. }
  48456. else if (!sprite.isPickable) {
  48457. continue;
  48458. }
  48459. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48460. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48461. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48462. if (ray.intersectsBoxMinMax(min, max)) {
  48463. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48464. if (distance > currentDistance) {
  48465. distance = currentDistance;
  48466. currentSprite = sprite;
  48467. if (fastCheck) {
  48468. break;
  48469. }
  48470. }
  48471. }
  48472. }
  48473. if (currentSprite) {
  48474. var result = new BABYLON.PickingInfo();
  48475. result.hit = true;
  48476. result.pickedSprite = currentSprite;
  48477. result.distance = distance;
  48478. return result;
  48479. }
  48480. return null;
  48481. };
  48482. SpriteManager.prototype.render = function () {
  48483. // Check
  48484. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48485. return;
  48486. var engine = this._scene.getEngine();
  48487. var baseSize = this._spriteTexture.getBaseSize();
  48488. // Sprites
  48489. var deltaTime = engine.getDeltaTime();
  48490. var max = Math.min(this._capacity, this.sprites.length);
  48491. var rowSize = baseSize.width / this.cellWidth;
  48492. var offset = 0;
  48493. for (var index = 0; index < max; index++) {
  48494. var sprite = this.sprites[index];
  48495. if (!sprite) {
  48496. continue;
  48497. }
  48498. sprite._animate(deltaTime);
  48499. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48500. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48501. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48502. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48503. }
  48504. this._buffer.update(this._vertexData);
  48505. // Render
  48506. var effect = this._effectBase;
  48507. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48508. effect = this._effectFog;
  48509. }
  48510. engine.enableEffect(effect);
  48511. var viewMatrix = this._scene.getViewMatrix();
  48512. effect.setTexture("diffuseSampler", this._spriteTexture);
  48513. effect.setMatrix("view", viewMatrix);
  48514. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48515. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48516. // Fog
  48517. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48518. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48519. effect.setColor3("vFogColor", this._scene.fogColor);
  48520. }
  48521. // VBOs
  48522. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48523. // Draw order
  48524. engine.setDepthFunctionToLessOrEqual();
  48525. effect.setBool("alphaTest", true);
  48526. engine.setColorWrite(false);
  48527. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48528. engine.setColorWrite(true);
  48529. effect.setBool("alphaTest", false);
  48530. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48531. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48532. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48533. };
  48534. SpriteManager.prototype.dispose = function () {
  48535. if (this._buffer) {
  48536. this._buffer.dispose();
  48537. this._buffer = null;
  48538. }
  48539. if (this._indexBuffer) {
  48540. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48541. this._indexBuffer = null;
  48542. }
  48543. if (this._spriteTexture) {
  48544. this._spriteTexture.dispose();
  48545. this._spriteTexture = null;
  48546. }
  48547. // Remove from scene
  48548. var index = this._scene.spriteManagers.indexOf(this);
  48549. this._scene.spriteManagers.splice(index, 1);
  48550. // Callback
  48551. this.onDisposeObservable.notifyObservers(this);
  48552. this.onDisposeObservable.clear();
  48553. };
  48554. return SpriteManager;
  48555. }());
  48556. BABYLON.SpriteManager = SpriteManager;
  48557. })(BABYLON || (BABYLON = {}));
  48558. //# sourceMappingURL=babylon.spriteManager.js.map
  48559. var BABYLON;
  48560. (function (BABYLON) {
  48561. var Sprite = /** @class */ (function () {
  48562. function Sprite(name, manager) {
  48563. this.name = name;
  48564. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48565. this.width = 1.0;
  48566. this.height = 1.0;
  48567. this.angle = 0;
  48568. this.cellIndex = 0;
  48569. this.invertU = 0;
  48570. this.invertV = 0;
  48571. this.animations = new Array();
  48572. this.isPickable = false;
  48573. this._animationStarted = false;
  48574. this._loopAnimation = false;
  48575. this._fromIndex = 0;
  48576. this._toIndex = 0;
  48577. this._delay = 0;
  48578. this._direction = 1;
  48579. this._time = 0;
  48580. this._manager = manager;
  48581. this._manager.sprites.push(this);
  48582. this.position = BABYLON.Vector3.Zero();
  48583. }
  48584. Object.defineProperty(Sprite.prototype, "size", {
  48585. get: function () {
  48586. return this.width;
  48587. },
  48588. set: function (value) {
  48589. this.width = value;
  48590. this.height = value;
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48596. this._fromIndex = from;
  48597. this._toIndex = to;
  48598. this._loopAnimation = loop;
  48599. this._delay = delay;
  48600. this._animationStarted = true;
  48601. this._direction = from < to ? 1 : -1;
  48602. this.cellIndex = from;
  48603. this._time = 0;
  48604. this._onAnimationEnd = onAnimationEnd;
  48605. };
  48606. Sprite.prototype.stopAnimation = function () {
  48607. this._animationStarted = false;
  48608. };
  48609. Sprite.prototype._animate = function (deltaTime) {
  48610. if (!this._animationStarted)
  48611. return;
  48612. this._time += deltaTime;
  48613. if (this._time > this._delay) {
  48614. this._time = this._time % this._delay;
  48615. this.cellIndex += this._direction;
  48616. if (this.cellIndex > this._toIndex) {
  48617. if (this._loopAnimation) {
  48618. this.cellIndex = this._fromIndex;
  48619. }
  48620. else {
  48621. this.cellIndex = this._toIndex;
  48622. this._animationStarted = false;
  48623. if (this._onAnimationEnd) {
  48624. this._onAnimationEnd();
  48625. }
  48626. if (this.disposeWhenFinishedAnimating) {
  48627. this.dispose();
  48628. }
  48629. }
  48630. }
  48631. }
  48632. };
  48633. Sprite.prototype.dispose = function () {
  48634. for (var i = 0; i < this._manager.sprites.length; i++) {
  48635. if (this._manager.sprites[i] == this) {
  48636. this._manager.sprites.splice(i, 1);
  48637. }
  48638. }
  48639. };
  48640. return Sprite;
  48641. }());
  48642. BABYLON.Sprite = Sprite;
  48643. })(BABYLON || (BABYLON = {}));
  48644. //# sourceMappingURL=babylon.sprite.js.map
  48645. var BABYLON;
  48646. (function (BABYLON) {
  48647. var IntersectionInfo = /** @class */ (function () {
  48648. function IntersectionInfo(bu, bv, distance) {
  48649. this.bu = bu;
  48650. this.bv = bv;
  48651. this.distance = distance;
  48652. this.faceId = 0;
  48653. this.subMeshId = 0;
  48654. }
  48655. return IntersectionInfo;
  48656. }());
  48657. BABYLON.IntersectionInfo = IntersectionInfo;
  48658. var PickingInfo = /** @class */ (function () {
  48659. function PickingInfo() {
  48660. this.hit = false;
  48661. this.distance = 0;
  48662. this.pickedPoint = null;
  48663. this.pickedMesh = null;
  48664. this.bu = 0;
  48665. this.bv = 0;
  48666. this.faceId = -1;
  48667. this.subMeshId = 0;
  48668. this.pickedSprite = null;
  48669. }
  48670. // Methods
  48671. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48672. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48673. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48674. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48675. return null;
  48676. }
  48677. var indices = this.pickedMesh.getIndices();
  48678. if (!indices) {
  48679. return null;
  48680. }
  48681. var result;
  48682. if (useVerticesNormals) {
  48683. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48684. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48685. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48686. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48687. normal0 = normal0.scale(this.bu);
  48688. normal1 = normal1.scale(this.bv);
  48689. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48690. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48691. }
  48692. else {
  48693. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48694. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48695. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48696. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48697. var p1p2 = vertex1.subtract(vertex2);
  48698. var p3p2 = vertex3.subtract(vertex2);
  48699. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48700. }
  48701. if (useWorldCoordinates) {
  48702. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48703. }
  48704. return BABYLON.Vector3.Normalize(result);
  48705. };
  48706. PickingInfo.prototype.getTextureCoordinates = function () {
  48707. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48708. return null;
  48709. }
  48710. var indices = this.pickedMesh.getIndices();
  48711. if (!indices) {
  48712. return null;
  48713. }
  48714. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48715. if (!uvs) {
  48716. return null;
  48717. }
  48718. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48719. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48720. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48721. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48722. uv1 = uv1.scale(this.bu);
  48723. uv2 = uv2.scale(this.bv);
  48724. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48725. };
  48726. return PickingInfo;
  48727. }());
  48728. BABYLON.PickingInfo = PickingInfo;
  48729. })(BABYLON || (BABYLON = {}));
  48730. //# sourceMappingURL=babylon.pickingInfo.js.map
  48731. var BABYLON;
  48732. (function (BABYLON) {
  48733. var Ray = /** @class */ (function () {
  48734. function Ray(origin, direction, length) {
  48735. if (length === void 0) { length = Number.MAX_VALUE; }
  48736. this.origin = origin;
  48737. this.direction = direction;
  48738. this.length = length;
  48739. }
  48740. // Methods
  48741. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48742. var d = 0.0;
  48743. var maxValue = Number.MAX_VALUE;
  48744. var inv;
  48745. var min;
  48746. var max;
  48747. var temp;
  48748. if (Math.abs(this.direction.x) < 0.0000001) {
  48749. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48750. return false;
  48751. }
  48752. }
  48753. else {
  48754. inv = 1.0 / this.direction.x;
  48755. min = (minimum.x - this.origin.x) * inv;
  48756. max = (maximum.x - this.origin.x) * inv;
  48757. if (max === -Infinity) {
  48758. max = Infinity;
  48759. }
  48760. if (min > max) {
  48761. temp = min;
  48762. min = max;
  48763. max = temp;
  48764. }
  48765. d = Math.max(min, d);
  48766. maxValue = Math.min(max, maxValue);
  48767. if (d > maxValue) {
  48768. return false;
  48769. }
  48770. }
  48771. if (Math.abs(this.direction.y) < 0.0000001) {
  48772. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48773. return false;
  48774. }
  48775. }
  48776. else {
  48777. inv = 1.0 / this.direction.y;
  48778. min = (minimum.y - this.origin.y) * inv;
  48779. max = (maximum.y - this.origin.y) * inv;
  48780. if (max === -Infinity) {
  48781. max = Infinity;
  48782. }
  48783. if (min > max) {
  48784. temp = min;
  48785. min = max;
  48786. max = temp;
  48787. }
  48788. d = Math.max(min, d);
  48789. maxValue = Math.min(max, maxValue);
  48790. if (d > maxValue) {
  48791. return false;
  48792. }
  48793. }
  48794. if (Math.abs(this.direction.z) < 0.0000001) {
  48795. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48796. return false;
  48797. }
  48798. }
  48799. else {
  48800. inv = 1.0 / this.direction.z;
  48801. min = (minimum.z - this.origin.z) * inv;
  48802. max = (maximum.z - this.origin.z) * inv;
  48803. if (max === -Infinity) {
  48804. max = Infinity;
  48805. }
  48806. if (min > max) {
  48807. temp = min;
  48808. min = max;
  48809. max = temp;
  48810. }
  48811. d = Math.max(min, d);
  48812. maxValue = Math.min(max, maxValue);
  48813. if (d > maxValue) {
  48814. return false;
  48815. }
  48816. }
  48817. return true;
  48818. };
  48819. Ray.prototype.intersectsBox = function (box) {
  48820. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48821. };
  48822. Ray.prototype.intersectsSphere = function (sphere) {
  48823. var x = sphere.center.x - this.origin.x;
  48824. var y = sphere.center.y - this.origin.y;
  48825. var z = sphere.center.z - this.origin.z;
  48826. var pyth = (x * x) + (y * y) + (z * z);
  48827. var rr = sphere.radius * sphere.radius;
  48828. if (pyth <= rr) {
  48829. return true;
  48830. }
  48831. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48832. if (dot < 0.0) {
  48833. return false;
  48834. }
  48835. var temp = pyth - (dot * dot);
  48836. return temp <= rr;
  48837. };
  48838. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48839. if (!this._edge1) {
  48840. this._edge1 = BABYLON.Vector3.Zero();
  48841. this._edge2 = BABYLON.Vector3.Zero();
  48842. this._pvec = BABYLON.Vector3.Zero();
  48843. this._tvec = BABYLON.Vector3.Zero();
  48844. this._qvec = BABYLON.Vector3.Zero();
  48845. }
  48846. vertex1.subtractToRef(vertex0, this._edge1);
  48847. vertex2.subtractToRef(vertex0, this._edge2);
  48848. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48849. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48850. if (det === 0) {
  48851. return null;
  48852. }
  48853. var invdet = 1 / det;
  48854. this.origin.subtractToRef(vertex0, this._tvec);
  48855. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48856. if (bu < 0 || bu > 1.0) {
  48857. return null;
  48858. }
  48859. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48860. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48861. if (bv < 0 || bu + bv > 1.0) {
  48862. return null;
  48863. }
  48864. //check if the distance is longer than the predefined length.
  48865. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48866. if (distance > this.length) {
  48867. return null;
  48868. }
  48869. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48870. };
  48871. Ray.prototype.intersectsPlane = function (plane) {
  48872. var distance;
  48873. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48874. if (Math.abs(result1) < 9.99999997475243E-07) {
  48875. return null;
  48876. }
  48877. else {
  48878. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48879. distance = (-plane.d - result2) / result1;
  48880. if (distance < 0.0) {
  48881. if (distance < -9.99999997475243E-07) {
  48882. return null;
  48883. }
  48884. else {
  48885. return 0;
  48886. }
  48887. }
  48888. return distance;
  48889. }
  48890. };
  48891. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  48892. var tm = BABYLON.Tmp.Matrix[0];
  48893. mesh.getWorldMatrix().invertToRef(tm);
  48894. if (this._tmpRay) {
  48895. Ray.TransformToRef(this, tm, this._tmpRay);
  48896. }
  48897. else {
  48898. this._tmpRay = Ray.Transform(this, tm);
  48899. }
  48900. return mesh.intersects(this._tmpRay, fastCheck);
  48901. };
  48902. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  48903. if (results) {
  48904. results.length = 0;
  48905. }
  48906. else {
  48907. results = [];
  48908. }
  48909. for (var i = 0; i < meshes.length; i++) {
  48910. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  48911. if (pickInfo.hit) {
  48912. results.push(pickInfo);
  48913. }
  48914. }
  48915. results.sort(this._comparePickingInfo);
  48916. return results;
  48917. };
  48918. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  48919. if (pickingInfoA.distance < pickingInfoB.distance) {
  48920. return -1;
  48921. }
  48922. else if (pickingInfoA.distance > pickingInfoB.distance) {
  48923. return 1;
  48924. }
  48925. else {
  48926. return 0;
  48927. }
  48928. };
  48929. /**
  48930. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  48931. * @param sega the first point of the segment to test the intersection against
  48932. * @param segb the second point of the segment to test the intersection against
  48933. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  48934. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  48935. */
  48936. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  48937. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  48938. var u = segb.subtract(sega);
  48939. var v = rsegb.subtract(this.origin);
  48940. var w = sega.subtract(this.origin);
  48941. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  48942. var b = BABYLON.Vector3.Dot(u, v);
  48943. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  48944. var d = BABYLON.Vector3.Dot(u, w);
  48945. var e = BABYLON.Vector3.Dot(v, w);
  48946. var D = a * c - b * b; // always >= 0
  48947. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  48948. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  48949. // compute the line parameters of the two closest points
  48950. if (D < Ray.smallnum) {
  48951. sN = 0.0; // force using point P0 on segment S1
  48952. sD = 1.0; // to prevent possible division by 0.0 later
  48953. tN = e;
  48954. tD = c;
  48955. }
  48956. else {
  48957. sN = (b * e - c * d);
  48958. tN = (a * e - b * d);
  48959. if (sN < 0.0) {
  48960. sN = 0.0;
  48961. tN = e;
  48962. tD = c;
  48963. }
  48964. else if (sN > sD) {
  48965. sN = sD;
  48966. tN = e + b;
  48967. tD = c;
  48968. }
  48969. }
  48970. if (tN < 0.0) {
  48971. tN = 0.0;
  48972. // recompute sc for this edge
  48973. if (-d < 0.0) {
  48974. sN = 0.0;
  48975. }
  48976. else if (-d > a)
  48977. sN = sD;
  48978. else {
  48979. sN = -d;
  48980. sD = a;
  48981. }
  48982. }
  48983. else if (tN > tD) {
  48984. tN = tD;
  48985. // recompute sc for this edge
  48986. if ((-d + b) < 0.0) {
  48987. sN = 0;
  48988. }
  48989. else if ((-d + b) > a) {
  48990. sN = sD;
  48991. }
  48992. else {
  48993. sN = (-d + b);
  48994. sD = a;
  48995. }
  48996. }
  48997. // finally do the division to get sc and tc
  48998. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  48999. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49000. // get the difference of the two closest points
  49001. var qtc = v.multiplyByFloats(tc, tc, tc);
  49002. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49003. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49004. if (isIntersected) {
  49005. return qtc.length();
  49006. }
  49007. return -1;
  49008. };
  49009. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49010. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49011. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49012. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49013. this.direction.normalize();
  49014. return this;
  49015. };
  49016. // Statics
  49017. Ray.Zero = function () {
  49018. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49019. };
  49020. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49021. var result = Ray.Zero();
  49022. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49023. };
  49024. /**
  49025. * 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
  49026. * transformed to the given world matrix.
  49027. * @param origin The origin point
  49028. * @param end The end point
  49029. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49030. */
  49031. Ray.CreateNewFromTo = function (origin, end, world) {
  49032. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49033. var direction = end.subtract(origin);
  49034. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49035. direction.normalize();
  49036. return Ray.Transform(new Ray(origin, direction, length), world);
  49037. };
  49038. Ray.Transform = function (ray, matrix) {
  49039. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49040. Ray.TransformToRef(ray, matrix, result);
  49041. return result;
  49042. };
  49043. Ray.TransformToRef = function (ray, matrix, result) {
  49044. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49045. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49046. result.length = ray.length;
  49047. var dir = result.direction;
  49048. var len = dir.length();
  49049. if (!(len === 0 || len === 1)) {
  49050. var num = 1.0 / len;
  49051. dir.x *= num;
  49052. dir.y *= num;
  49053. dir.z *= num;
  49054. result.length *= len;
  49055. }
  49056. };
  49057. Ray.smallnum = 0.00000001;
  49058. Ray.rayl = 10e8;
  49059. return Ray;
  49060. }());
  49061. BABYLON.Ray = Ray;
  49062. })(BABYLON || (BABYLON = {}));
  49063. //# sourceMappingURL=babylon.ray.js.map
  49064. var BABYLON;
  49065. (function (BABYLON) {
  49066. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49067. if (boxMin.x > sphereCenter.x + sphereRadius)
  49068. return false;
  49069. if (sphereCenter.x - sphereRadius > boxMax.x)
  49070. return false;
  49071. if (boxMin.y > sphereCenter.y + sphereRadius)
  49072. return false;
  49073. if (sphereCenter.y - sphereRadius > boxMax.y)
  49074. return false;
  49075. if (boxMin.z > sphereCenter.z + sphereRadius)
  49076. return false;
  49077. if (sphereCenter.z - sphereRadius > boxMax.z)
  49078. return false;
  49079. return true;
  49080. };
  49081. var getLowestRoot = (function () {
  49082. var result = { root: 0, found: false };
  49083. return function (a, b, c, maxR) {
  49084. result.root = 0;
  49085. result.found = false;
  49086. var determinant = b * b - 4.0 * a * c;
  49087. if (determinant < 0)
  49088. return result;
  49089. var sqrtD = Math.sqrt(determinant);
  49090. var r1 = (-b - sqrtD) / (2.0 * a);
  49091. var r2 = (-b + sqrtD) / (2.0 * a);
  49092. if (r1 > r2) {
  49093. var temp = r2;
  49094. r2 = r1;
  49095. r1 = temp;
  49096. }
  49097. if (r1 > 0 && r1 < maxR) {
  49098. result.root = r1;
  49099. result.found = true;
  49100. return result;
  49101. }
  49102. if (r2 > 0 && r2 < maxR) {
  49103. result.root = r2;
  49104. result.found = true;
  49105. return result;
  49106. }
  49107. return result;
  49108. };
  49109. })();
  49110. var Collider = /** @class */ (function () {
  49111. function Collider() {
  49112. this._collisionPoint = BABYLON.Vector3.Zero();
  49113. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49114. this._tempVector = BABYLON.Vector3.Zero();
  49115. this._tempVector2 = BABYLON.Vector3.Zero();
  49116. this._tempVector3 = BABYLON.Vector3.Zero();
  49117. this._tempVector4 = BABYLON.Vector3.Zero();
  49118. this._edge = BABYLON.Vector3.Zero();
  49119. this._baseToVertex = BABYLON.Vector3.Zero();
  49120. this._destinationPoint = BABYLON.Vector3.Zero();
  49121. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49122. this._displacementVector = BABYLON.Vector3.Zero();
  49123. this._radius = BABYLON.Vector3.One();
  49124. this._retry = 0;
  49125. this._basePointWorld = BABYLON.Vector3.Zero();
  49126. this._velocityWorld = BABYLON.Vector3.Zero();
  49127. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49128. this._collisionMask = -1;
  49129. }
  49130. Object.defineProperty(Collider.prototype, "collisionMask", {
  49131. get: function () {
  49132. return this._collisionMask;
  49133. },
  49134. set: function (mask) {
  49135. this._collisionMask = !isNaN(mask) ? mask : -1;
  49136. },
  49137. enumerable: true,
  49138. configurable: true
  49139. });
  49140. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49141. /**
  49142. * Gets the plane normal used to compute the sliding response (in local space)
  49143. */
  49144. get: function () {
  49145. return this._slidePlaneNormal;
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. // Methods
  49151. Collider.prototype._initialize = function (source, dir, e) {
  49152. this._velocity = dir;
  49153. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49154. this._basePoint = source;
  49155. source.multiplyToRef(this._radius, this._basePointWorld);
  49156. dir.multiplyToRef(this._radius, this._velocityWorld);
  49157. this._velocityWorldLength = this._velocityWorld.length();
  49158. this._epsilon = e;
  49159. this.collisionFound = false;
  49160. };
  49161. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49162. pa.subtractToRef(point, this._tempVector);
  49163. pb.subtractToRef(point, this._tempVector2);
  49164. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49165. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49166. if (d < 0)
  49167. return false;
  49168. pc.subtractToRef(point, this._tempVector3);
  49169. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49170. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49171. if (d < 0)
  49172. return false;
  49173. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49174. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49175. return d >= 0;
  49176. };
  49177. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49178. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49179. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49180. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49181. return false;
  49182. }
  49183. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49184. return false;
  49185. return true;
  49186. };
  49187. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49188. var t0;
  49189. var embeddedInPlane = false;
  49190. //defensive programming, actually not needed.
  49191. if (!trianglePlaneArray) {
  49192. trianglePlaneArray = [];
  49193. }
  49194. if (!trianglePlaneArray[faceIndex]) {
  49195. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49196. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49197. }
  49198. var trianglePlane = trianglePlaneArray[faceIndex];
  49199. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49200. return;
  49201. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49202. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49203. if (normalDotVelocity == 0) {
  49204. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49205. return;
  49206. embeddedInPlane = true;
  49207. t0 = 0;
  49208. }
  49209. else {
  49210. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49211. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49212. if (t0 > t1) {
  49213. var temp = t1;
  49214. t1 = t0;
  49215. t0 = temp;
  49216. }
  49217. if (t0 > 1.0 || t1 < 0.0)
  49218. return;
  49219. if (t0 < 0)
  49220. t0 = 0;
  49221. if (t0 > 1.0)
  49222. t0 = 1.0;
  49223. }
  49224. this._collisionPoint.copyFromFloats(0, 0, 0);
  49225. var found = false;
  49226. var t = 1.0;
  49227. if (!embeddedInPlane) {
  49228. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49229. this._velocity.scaleToRef(t0, this._tempVector);
  49230. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49231. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49232. found = true;
  49233. t = t0;
  49234. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49235. }
  49236. }
  49237. if (!found) {
  49238. var velocitySquaredLength = this._velocity.lengthSquared();
  49239. var a = velocitySquaredLength;
  49240. this._basePoint.subtractToRef(p1, this._tempVector);
  49241. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49242. var c = this._tempVector.lengthSquared() - 1.0;
  49243. var lowestRoot = getLowestRoot(a, b, c, t);
  49244. if (lowestRoot.found) {
  49245. t = lowestRoot.root;
  49246. found = true;
  49247. this._collisionPoint.copyFrom(p1);
  49248. }
  49249. this._basePoint.subtractToRef(p2, this._tempVector);
  49250. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49251. c = this._tempVector.lengthSquared() - 1.0;
  49252. lowestRoot = getLowestRoot(a, b, c, t);
  49253. if (lowestRoot.found) {
  49254. t = lowestRoot.root;
  49255. found = true;
  49256. this._collisionPoint.copyFrom(p2);
  49257. }
  49258. this._basePoint.subtractToRef(p3, this._tempVector);
  49259. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49260. c = this._tempVector.lengthSquared() - 1.0;
  49261. lowestRoot = getLowestRoot(a, b, c, t);
  49262. if (lowestRoot.found) {
  49263. t = lowestRoot.root;
  49264. found = true;
  49265. this._collisionPoint.copyFrom(p3);
  49266. }
  49267. p2.subtractToRef(p1, this._edge);
  49268. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49269. var edgeSquaredLength = this._edge.lengthSquared();
  49270. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49271. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49272. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49273. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49274. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49275. lowestRoot = getLowestRoot(a, b, c, t);
  49276. if (lowestRoot.found) {
  49277. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49278. if (f >= 0.0 && f <= 1.0) {
  49279. t = lowestRoot.root;
  49280. found = true;
  49281. this._edge.scaleInPlace(f);
  49282. p1.addToRef(this._edge, this._collisionPoint);
  49283. }
  49284. }
  49285. p3.subtractToRef(p2, this._edge);
  49286. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49287. edgeSquaredLength = this._edge.lengthSquared();
  49288. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49289. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49290. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49291. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49292. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49293. lowestRoot = getLowestRoot(a, b, c, t);
  49294. if (lowestRoot.found) {
  49295. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49296. if (f >= 0.0 && f <= 1.0) {
  49297. t = lowestRoot.root;
  49298. found = true;
  49299. this._edge.scaleInPlace(f);
  49300. p2.addToRef(this._edge, this._collisionPoint);
  49301. }
  49302. }
  49303. p1.subtractToRef(p3, this._edge);
  49304. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49305. edgeSquaredLength = this._edge.lengthSquared();
  49306. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49307. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49308. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49309. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49310. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49311. lowestRoot = getLowestRoot(a, b, c, t);
  49312. if (lowestRoot.found) {
  49313. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49314. if (f >= 0.0 && f <= 1.0) {
  49315. t = lowestRoot.root;
  49316. found = true;
  49317. this._edge.scaleInPlace(f);
  49318. p3.addToRef(this._edge, this._collisionPoint);
  49319. }
  49320. }
  49321. }
  49322. if (found) {
  49323. var distToCollision = t * this._velocity.length();
  49324. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49325. if (!this.intersectionPoint) {
  49326. this.intersectionPoint = this._collisionPoint.clone();
  49327. }
  49328. else {
  49329. this.intersectionPoint.copyFrom(this._collisionPoint);
  49330. }
  49331. this._nearestDistance = distToCollision;
  49332. this.collisionFound = true;
  49333. }
  49334. }
  49335. };
  49336. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49337. for (var i = indexStart; i < indexEnd; i += 3) {
  49338. var p1 = pts[indices[i] - decal];
  49339. var p2 = pts[indices[i + 1] - decal];
  49340. var p3 = pts[indices[i + 2] - decal];
  49341. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49342. }
  49343. };
  49344. Collider.prototype._getResponse = function (pos, vel) {
  49345. pos.addToRef(vel, this._destinationPoint);
  49346. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49347. this._basePoint.addToRef(vel, pos);
  49348. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49349. this._slidePlaneNormal.normalize();
  49350. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49351. pos.addInPlace(this._displacementVector);
  49352. this.intersectionPoint.addInPlace(this._displacementVector);
  49353. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49354. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49355. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49356. };
  49357. return Collider;
  49358. }());
  49359. BABYLON.Collider = Collider;
  49360. })(BABYLON || (BABYLON = {}));
  49361. //# sourceMappingURL=babylon.collider.js.map
  49362. var BABYLON;
  49363. (function (BABYLON) {
  49364. //WebWorker code will be inserted to this variable.
  49365. BABYLON.CollisionWorker = "";
  49366. var WorkerTaskType;
  49367. (function (WorkerTaskType) {
  49368. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49369. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49370. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49371. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49372. var WorkerReplyType;
  49373. (function (WorkerReplyType) {
  49374. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49375. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49376. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49377. var CollisionCoordinatorWorker = /** @class */ (function () {
  49378. function CollisionCoordinatorWorker() {
  49379. var _this = this;
  49380. this._scaledPosition = BABYLON.Vector3.Zero();
  49381. this._scaledVelocity = BABYLON.Vector3.Zero();
  49382. this.onMeshUpdated = function (transformNode) {
  49383. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49384. };
  49385. this.onGeometryUpdated = function (geometry) {
  49386. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49387. };
  49388. this._afterRender = function () {
  49389. if (!_this._init)
  49390. return;
  49391. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49392. return;
  49393. }
  49394. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49395. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49396. if (_this._runningUpdated > 4) {
  49397. return;
  49398. }
  49399. ++_this._runningUpdated;
  49400. var payload = {
  49401. updatedMeshes: _this._addUpdateMeshesList,
  49402. updatedGeometries: _this._addUpdateGeometriesList,
  49403. removedGeometries: _this._toRemoveGeometryArray,
  49404. removedMeshes: _this._toRemoveMeshesArray
  49405. };
  49406. var message = {
  49407. payload: payload,
  49408. taskType: WorkerTaskType.UPDATE
  49409. };
  49410. var serializable = [];
  49411. for (var id in payload.updatedGeometries) {
  49412. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49413. //prepare transferables
  49414. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49415. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49416. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49417. }
  49418. }
  49419. _this._worker.postMessage(message, serializable);
  49420. _this._addUpdateMeshesList = {};
  49421. _this._addUpdateGeometriesList = {};
  49422. _this._toRemoveGeometryArray = [];
  49423. _this._toRemoveMeshesArray = [];
  49424. };
  49425. this._onMessageFromWorker = function (e) {
  49426. var returnData = e.data;
  49427. if (returnData.error != WorkerReplyType.SUCCESS) {
  49428. //TODO what errors can be returned from the worker?
  49429. BABYLON.Tools.Warn("error returned from worker!");
  49430. return;
  49431. }
  49432. switch (returnData.taskType) {
  49433. case WorkerTaskType.INIT:
  49434. _this._init = true;
  49435. //Update the worked with ALL of the scene's current state
  49436. _this._scene.meshes.forEach(function (mesh) {
  49437. _this.onMeshAdded(mesh);
  49438. });
  49439. _this._scene.getGeometries().forEach(function (geometry) {
  49440. _this.onGeometryAdded(geometry);
  49441. });
  49442. break;
  49443. case WorkerTaskType.UPDATE:
  49444. _this._runningUpdated--;
  49445. break;
  49446. case WorkerTaskType.COLLIDE:
  49447. var returnPayload = returnData.payload;
  49448. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49449. return;
  49450. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49451. if (callback) {
  49452. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49453. if (mesh) {
  49454. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49455. }
  49456. }
  49457. //cleanup
  49458. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49459. break;
  49460. }
  49461. };
  49462. this._collisionsCallbackArray = [];
  49463. this._init = false;
  49464. this._runningUpdated = 0;
  49465. this._addUpdateMeshesList = {};
  49466. this._addUpdateGeometriesList = {};
  49467. this._toRemoveGeometryArray = [];
  49468. this._toRemoveMeshesArray = [];
  49469. }
  49470. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49471. if (!this._init)
  49472. return;
  49473. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49474. return;
  49475. position.divideToRef(collider._radius, this._scaledPosition);
  49476. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49477. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49478. var payload = {
  49479. collider: {
  49480. position: this._scaledPosition.asArray(),
  49481. velocity: this._scaledVelocity.asArray(),
  49482. radius: collider._radius.asArray()
  49483. },
  49484. collisionId: collisionIndex,
  49485. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49486. maximumRetry: maximumRetry
  49487. };
  49488. var message = {
  49489. payload: payload,
  49490. taskType: WorkerTaskType.COLLIDE
  49491. };
  49492. this._worker.postMessage(message);
  49493. };
  49494. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49495. this._scene = scene;
  49496. this._scene.registerAfterRender(this._afterRender);
  49497. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49498. this._worker = new Worker(workerUrl);
  49499. this._worker.onmessage = this._onMessageFromWorker;
  49500. var message = {
  49501. payload: {},
  49502. taskType: WorkerTaskType.INIT
  49503. };
  49504. this._worker.postMessage(message);
  49505. };
  49506. CollisionCoordinatorWorker.prototype.destroy = function () {
  49507. this._scene.unregisterAfterRender(this._afterRender);
  49508. this._worker.terminate();
  49509. };
  49510. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49511. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49512. this.onMeshUpdated(mesh);
  49513. };
  49514. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49515. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49516. };
  49517. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49518. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49519. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49520. this.onGeometryUpdated(geometry);
  49521. };
  49522. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49523. this._toRemoveGeometryArray.push(geometry.id);
  49524. };
  49525. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49526. var submeshes = [];
  49527. if (mesh.subMeshes) {
  49528. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49529. var boundingInfo = sm.getBoundingInfo();
  49530. return {
  49531. position: idx,
  49532. verticesStart: sm.verticesStart,
  49533. verticesCount: sm.verticesCount,
  49534. indexStart: sm.indexStart,
  49535. indexCount: sm.indexCount,
  49536. hasMaterial: !!sm.getMaterial(),
  49537. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49538. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49539. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49540. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49541. };
  49542. });
  49543. }
  49544. var geometryId = null;
  49545. if (mesh instanceof BABYLON.Mesh) {
  49546. var geometry = mesh.geometry;
  49547. geometryId = geometry ? geometry.id : null;
  49548. }
  49549. else if (mesh instanceof BABYLON.InstancedMesh) {
  49550. var geometry = mesh.sourceMesh.geometry;
  49551. geometryId = geometry ? geometry.id : null;
  49552. }
  49553. var boundingInfo = mesh.getBoundingInfo();
  49554. return {
  49555. uniqueId: mesh.uniqueId,
  49556. id: mesh.id,
  49557. name: mesh.name,
  49558. geometryId: geometryId,
  49559. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49560. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49561. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49562. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49563. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49564. subMeshes: submeshes,
  49565. checkCollisions: mesh.checkCollisions
  49566. };
  49567. };
  49568. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49569. return {
  49570. id: geometry.id,
  49571. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49572. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49573. indices: new Uint32Array(geometry.getIndices() || []),
  49574. };
  49575. };
  49576. return CollisionCoordinatorWorker;
  49577. }());
  49578. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49579. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49580. function CollisionCoordinatorLegacy() {
  49581. this._scaledPosition = BABYLON.Vector3.Zero();
  49582. this._scaledVelocity = BABYLON.Vector3.Zero();
  49583. this._finalPosition = BABYLON.Vector3.Zero();
  49584. }
  49585. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49586. position.divideToRef(collider._radius, this._scaledPosition);
  49587. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49588. collider.collidedMesh = null;
  49589. collider._retry = 0;
  49590. collider._initialVelocity = this._scaledVelocity;
  49591. collider._initialPosition = this._scaledPosition;
  49592. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49593. this._finalPosition.multiplyInPlace(collider._radius);
  49594. //run the callback
  49595. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49596. };
  49597. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49598. this._scene = scene;
  49599. };
  49600. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49601. //Legacy need no destruction method.
  49602. };
  49603. //No update in legacy mode
  49604. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49605. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49606. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49607. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49608. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49609. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49610. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49611. if (excludedMesh === void 0) { excludedMesh = null; }
  49612. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49613. if (collider._retry >= maximumRetry) {
  49614. finalPosition.copyFrom(position);
  49615. return;
  49616. }
  49617. // Check if this is a mesh else camera or -1
  49618. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49619. collider._initialize(position, velocity, closeDistance);
  49620. // Check all meshes
  49621. for (var index = 0; index < this._scene.meshes.length; index++) {
  49622. var mesh = this._scene.meshes[index];
  49623. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49624. mesh._checkCollision(collider);
  49625. }
  49626. }
  49627. if (!collider.collisionFound) {
  49628. position.addToRef(velocity, finalPosition);
  49629. return;
  49630. }
  49631. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49632. collider._getResponse(position, velocity);
  49633. }
  49634. if (velocity.length() <= closeDistance) {
  49635. finalPosition.copyFrom(position);
  49636. return;
  49637. }
  49638. collider._retry++;
  49639. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49640. };
  49641. return CollisionCoordinatorLegacy;
  49642. }());
  49643. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49644. })(BABYLON || (BABYLON = {}));
  49645. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49646. var BABYLON;
  49647. (function (BABYLON) {
  49648. /**
  49649. * A particle represents one of the element emitted by a particle system.
  49650. * This is mainly define by its coordinates, direction, velocity and age.
  49651. */
  49652. var Particle = /** @class */ (function () {
  49653. /**
  49654. * Creates a new instance of @see Particle
  49655. * @param particleSystem the particle system the particle belongs to
  49656. */
  49657. function Particle(particleSystem) {
  49658. this.particleSystem = particleSystem;
  49659. /**
  49660. * The world position of the particle in the scene.
  49661. */
  49662. this.position = BABYLON.Vector3.Zero();
  49663. /**
  49664. * The world direction of the particle in the scene.
  49665. */
  49666. this.direction = BABYLON.Vector3.Zero();
  49667. /**
  49668. * The color of the particle.
  49669. */
  49670. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49671. /**
  49672. * The color change of the particle per step.
  49673. */
  49674. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49675. /**
  49676. * Defines how long will the life of the particle be.
  49677. */
  49678. this.lifeTime = 1.0;
  49679. /**
  49680. * The current age of the particle.
  49681. */
  49682. this.age = 0;
  49683. /**
  49684. * The current size of the particle.
  49685. */
  49686. this.size = 0;
  49687. /**
  49688. * The current angle of the particle.
  49689. */
  49690. this.angle = 0;
  49691. /**
  49692. * Defines how fast is the angle changing.
  49693. */
  49694. this.angularSpeed = 0;
  49695. /**
  49696. * Defines the cell index used by the particle to be rendered from a sprite.
  49697. */
  49698. this.cellIndex = 0;
  49699. this._currentFrameCounter = 0;
  49700. if (!this.particleSystem.isAnimationSheetEnabled) {
  49701. return;
  49702. }
  49703. this.cellIndex = this.particleSystem.startSpriteCellID;
  49704. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49705. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49706. }
  49707. else {
  49708. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49709. }
  49710. }
  49711. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49712. // (ageOffset / scaledUpdateSpeed) / available cells
  49713. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49714. this._currentFrameCounter += scaledUpdateSpeed;
  49715. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49716. this._currentFrameCounter = 0;
  49717. this.cellIndex++;
  49718. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49719. this.cellIndex = this.particleSystem.endSpriteCellID;
  49720. }
  49721. }
  49722. };
  49723. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49724. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49725. this.cellIndex++;
  49726. this._currentFrameCounter = 0;
  49727. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49728. if (this.particleSystem.spriteCellLoop) {
  49729. this.cellIndex = this.particleSystem.startSpriteCellID;
  49730. }
  49731. else {
  49732. this.cellIndex = this.particleSystem.endSpriteCellID;
  49733. }
  49734. }
  49735. }
  49736. else {
  49737. this._currentFrameCounter++;
  49738. }
  49739. };
  49740. /**
  49741. * Copy the properties of particle to another one.
  49742. * @param other the particle to copy the information to.
  49743. */
  49744. Particle.prototype.copyTo = function (other) {
  49745. other.position.copyFrom(this.position);
  49746. other.direction.copyFrom(this.direction);
  49747. other.color.copyFrom(this.color);
  49748. other.colorStep.copyFrom(this.colorStep);
  49749. other.lifeTime = this.lifeTime;
  49750. other.age = this.age;
  49751. other.size = this.size;
  49752. other.angle = this.angle;
  49753. other.angularSpeed = this.angularSpeed;
  49754. other.particleSystem = this.particleSystem;
  49755. other.cellIndex = this.cellIndex;
  49756. };
  49757. return Particle;
  49758. }());
  49759. BABYLON.Particle = Particle;
  49760. })(BABYLON || (BABYLON = {}));
  49761. //# sourceMappingURL=babylon.particle.js.map
  49762. var BABYLON;
  49763. (function (BABYLON) {
  49764. /**
  49765. * This represents a particle system in Babylon.
  49766. * 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.
  49767. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49768. * @example https://doc.babylonjs.com/babylon101/particles
  49769. */
  49770. var ParticleSystem = /** @class */ (function () {
  49771. /**
  49772. * Instantiates a particle system.
  49773. * 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.
  49774. * @param name The name of the particle system
  49775. * @param capacity The max number of particles alive at the same time
  49776. * @param scene The scene the particle system belongs to
  49777. * @param customEffect a custom effect used to change the way particles are rendered by default
  49778. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49779. * @param epsilon Offset used to render the particles
  49780. */
  49781. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49782. if (customEffect === void 0) { customEffect = null; }
  49783. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49784. if (epsilon === void 0) { epsilon = 0.01; }
  49785. var _this = this;
  49786. /**
  49787. * List of animations used by the particle system.
  49788. */
  49789. this.animations = [];
  49790. /**
  49791. * The rendering group used by the Particle system to chose when to render.
  49792. */
  49793. this.renderingGroupId = 0;
  49794. /**
  49795. * The emitter represents the Mesh or position we are attaching the particle system to.
  49796. */
  49797. this.emitter = null;
  49798. /**
  49799. * The density of particles, the rate of particle flow
  49800. */
  49801. this.emitRate = 10;
  49802. /**
  49803. * If you want to launch only a few particles at once, that can be done, as well.
  49804. */
  49805. this.manualEmitCount = -1;
  49806. /**
  49807. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49808. */
  49809. this.updateSpeed = 0.01;
  49810. /**
  49811. * The amount of time the particle system is running (depends of the overall speed above).
  49812. */
  49813. this.targetStopDuration = 0;
  49814. /**
  49815. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49816. */
  49817. this.disposeOnStop = false;
  49818. /**
  49819. * Minimum power of emitting particles.
  49820. */
  49821. this.minEmitPower = 1;
  49822. /**
  49823. * Maximum power of emitting particles.
  49824. */
  49825. this.maxEmitPower = 1;
  49826. /**
  49827. * Minimum life time of emitting particles.
  49828. */
  49829. this.minLifeTime = 1;
  49830. /**
  49831. * Maximum life time of emitting particles.
  49832. */
  49833. this.maxLifeTime = 1;
  49834. /**
  49835. * Minimum Size of emitting particles.
  49836. */
  49837. this.minSize = 1;
  49838. /**
  49839. * Maximum Size of emitting particles.
  49840. */
  49841. this.maxSize = 1;
  49842. /**
  49843. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49844. */
  49845. this.minAngularSpeed = 0;
  49846. /**
  49847. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49848. */
  49849. this.maxAngularSpeed = 0;
  49850. /**
  49851. * The layer mask we are rendering the particles through.
  49852. */
  49853. this.layerMask = 0x0FFFFFFF;
  49854. /**
  49855. * This can help using your own shader to render the particle system.
  49856. * The according effect will be created
  49857. */
  49858. this.customShader = null;
  49859. /**
  49860. * By default particle system starts as soon as they are created. This prevents the
  49861. * automatic start to happen and let you decide when to start emitting particles.
  49862. */
  49863. this.preventAutoStart = false;
  49864. /**
  49865. * Callback triggered when the particle animation is ending.
  49866. */
  49867. this.onAnimationEnd = null;
  49868. /**
  49869. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49870. */
  49871. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49872. /**
  49873. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49874. * to override the particles.
  49875. */
  49876. this.forceDepthWrite = false;
  49877. /**
  49878. * You can use gravity if you want to give an orientation to your particles.
  49879. */
  49880. this.gravity = BABYLON.Vector3.Zero();
  49881. /**
  49882. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49883. */
  49884. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49885. /**
  49886. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49887. */
  49888. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49889. /**
  49890. * 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.
  49891. */
  49892. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  49893. /**
  49894. * 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.
  49895. */
  49896. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49897. /**
  49898. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49899. */
  49900. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49901. /**
  49902. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49903. */
  49904. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49905. /**
  49906. * Color the particle will have at the end of its lifetime.
  49907. */
  49908. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  49909. /**
  49910. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  49911. */
  49912. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49913. /**
  49914. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  49915. */
  49916. this.spriteCellLoop = true;
  49917. /**
  49918. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  49919. */
  49920. this.spriteCellChangeSpeed = 0;
  49921. /**
  49922. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  49923. */
  49924. this.startSpriteCellID = 0;
  49925. /**
  49926. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  49927. */
  49928. this.endSpriteCellID = 0;
  49929. /**
  49930. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  49931. */
  49932. this.spriteCellWidth = 0;
  49933. /**
  49934. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  49935. */
  49936. this.spriteCellHeight = 0;
  49937. /**
  49938. * An event triggered when the system is disposed.
  49939. */
  49940. this.onDisposeObservable = new BABYLON.Observable();
  49941. this._particles = new Array();
  49942. this._stockParticles = new Array();
  49943. this._newPartsExcess = 0;
  49944. this._vertexBuffers = {};
  49945. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  49946. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  49947. this._scaledDirection = BABYLON.Vector3.Zero();
  49948. this._scaledGravity = BABYLON.Vector3.Zero();
  49949. this._currentRenderId = -1;
  49950. this._started = false;
  49951. this._stopped = false;
  49952. this._actualFrame = 0;
  49953. this._vertexBufferSize = 11;
  49954. this._appendParticleVertexes = null;
  49955. this.id = name;
  49956. this.name = name;
  49957. this._capacity = capacity;
  49958. this._epsilon = epsilon;
  49959. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  49960. if (isAnimationSheetEnabled) {
  49961. this._vertexBufferSize = 12;
  49962. }
  49963. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49964. this._customEffect = customEffect;
  49965. scene.particleSystems.push(this);
  49966. this._createIndexBuffer();
  49967. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  49968. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  49969. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  49970. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  49971. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  49972. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  49973. if (this._isAnimationSheetEnabled) {
  49974. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  49975. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  49976. }
  49977. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49978. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49979. this._vertexBuffers["options"] = options;
  49980. // Default behaviors
  49981. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  49982. this.updateFunction = function (particles) {
  49983. for (var index = 0; index < particles.length; index++) {
  49984. var particle = particles[index];
  49985. particle.age += _this._scaledUpdateSpeed;
  49986. if (particle.age >= particle.lifeTime) {
  49987. _this.recycleParticle(particle);
  49988. index--;
  49989. continue;
  49990. }
  49991. else {
  49992. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  49993. particle.color.addInPlace(_this._scaledColorStep);
  49994. if (particle.color.a < 0)
  49995. particle.color.a = 0;
  49996. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  49997. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  49998. particle.position.addInPlace(_this._scaledDirection);
  49999. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50000. particle.direction.addInPlace(_this._scaledGravity);
  50001. if (_this._isAnimationSheetEnabled) {
  50002. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50003. }
  50004. }
  50005. }
  50006. };
  50007. }
  50008. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50009. /**
  50010. * Sets a callback that will be triggered when the system is disposed.
  50011. */
  50012. set: function (callback) {
  50013. if (this._onDisposeObserver) {
  50014. this.onDisposeObservable.remove(this._onDisposeObserver);
  50015. }
  50016. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50017. },
  50018. enumerable: true,
  50019. configurable: true
  50020. });
  50021. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50022. /**
  50023. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50024. */
  50025. get: function () {
  50026. return this._isAnimationSheetEnabled;
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. ParticleSystem.prototype._createIndexBuffer = function () {
  50032. var indices = [];
  50033. var index = 0;
  50034. for (var count = 0; count < this._capacity; count++) {
  50035. indices.push(index);
  50036. indices.push(index + 1);
  50037. indices.push(index + 2);
  50038. indices.push(index);
  50039. indices.push(index + 2);
  50040. indices.push(index + 3);
  50041. index += 4;
  50042. }
  50043. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50044. };
  50045. /**
  50046. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50047. * Its lifetime will start back at 0.
  50048. * @param particle The particle to recycle
  50049. */
  50050. ParticleSystem.prototype.recycleParticle = function (particle) {
  50051. var lastParticle = this._particles.pop();
  50052. if (lastParticle !== particle) {
  50053. lastParticle.copyTo(particle);
  50054. this._stockParticles.push(lastParticle);
  50055. }
  50056. };
  50057. /**
  50058. * Gets the maximum number of particles active at the same time.
  50059. * @returns The max number of active particles.
  50060. */
  50061. ParticleSystem.prototype.getCapacity = function () {
  50062. return this._capacity;
  50063. };
  50064. /**
  50065. * Gets Wether there are still active particles in the system.
  50066. * @returns True if it is alive, otherwise false.
  50067. */
  50068. ParticleSystem.prototype.isAlive = function () {
  50069. return this._alive;
  50070. };
  50071. /**
  50072. * Gets Wether the system has been started.
  50073. * @returns True if it has been started, otherwise false.
  50074. */
  50075. ParticleSystem.prototype.isStarted = function () {
  50076. return this._started;
  50077. };
  50078. /**
  50079. * Starts the particle system and begins to emit.
  50080. */
  50081. ParticleSystem.prototype.start = function () {
  50082. this._started = true;
  50083. this._stopped = false;
  50084. this._actualFrame = 0;
  50085. };
  50086. /**
  50087. * Stops the particle system.
  50088. */
  50089. ParticleSystem.prototype.stop = function () {
  50090. this._stopped = true;
  50091. };
  50092. /**
  50093. * @ignore (for internal use only)
  50094. */
  50095. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50096. var offset = index * this._vertexBufferSize;
  50097. this._vertexData[offset] = particle.position.x;
  50098. this._vertexData[offset + 1] = particle.position.y;
  50099. this._vertexData[offset + 2] = particle.position.z;
  50100. this._vertexData[offset + 3] = particle.color.r;
  50101. this._vertexData[offset + 4] = particle.color.g;
  50102. this._vertexData[offset + 5] = particle.color.b;
  50103. this._vertexData[offset + 6] = particle.color.a;
  50104. this._vertexData[offset + 7] = particle.angle;
  50105. this._vertexData[offset + 8] = particle.size;
  50106. this._vertexData[offset + 9] = offsetX;
  50107. this._vertexData[offset + 10] = offsetY;
  50108. };
  50109. /**
  50110. * @ignore (for internal use only)
  50111. */
  50112. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50113. if (offsetX === 0)
  50114. offsetX = this._epsilon;
  50115. else if (offsetX === 1)
  50116. offsetX = 1 - this._epsilon;
  50117. if (offsetY === 0)
  50118. offsetY = this._epsilon;
  50119. else if (offsetY === 1)
  50120. offsetY = 1 - this._epsilon;
  50121. var offset = index * this._vertexBufferSize;
  50122. this._vertexData[offset] = particle.position.x;
  50123. this._vertexData[offset + 1] = particle.position.y;
  50124. this._vertexData[offset + 2] = particle.position.z;
  50125. this._vertexData[offset + 3] = particle.color.r;
  50126. this._vertexData[offset + 4] = particle.color.g;
  50127. this._vertexData[offset + 5] = particle.color.b;
  50128. this._vertexData[offset + 6] = particle.color.a;
  50129. this._vertexData[offset + 7] = particle.angle;
  50130. this._vertexData[offset + 8] = particle.size;
  50131. this._vertexData[offset + 9] = offsetX;
  50132. this._vertexData[offset + 10] = offsetY;
  50133. this._vertexData[offset + 11] = particle.cellIndex;
  50134. };
  50135. ParticleSystem.prototype._update = function (newParticles) {
  50136. // Update current
  50137. this._alive = this._particles.length > 0;
  50138. this.updateFunction(this._particles);
  50139. // Add new ones
  50140. var worldMatrix;
  50141. if (this.emitter.position) {
  50142. var emitterMesh = this.emitter;
  50143. worldMatrix = emitterMesh.getWorldMatrix();
  50144. }
  50145. else {
  50146. var emitterPosition = this.emitter;
  50147. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50148. }
  50149. var particle;
  50150. for (var index = 0; index < newParticles; index++) {
  50151. if (this._particles.length === this._capacity) {
  50152. break;
  50153. }
  50154. if (this._stockParticles.length !== 0) {
  50155. particle = this._stockParticles.pop();
  50156. particle.age = 0;
  50157. particle.cellIndex = this.startSpriteCellID;
  50158. }
  50159. else {
  50160. particle = new BABYLON.Particle(this);
  50161. }
  50162. this._particles.push(particle);
  50163. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50164. if (this.startPositionFunction) {
  50165. this.startPositionFunction(worldMatrix, particle.position, particle);
  50166. }
  50167. else {
  50168. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50169. }
  50170. if (this.startDirectionFunction) {
  50171. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50172. }
  50173. else {
  50174. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50175. }
  50176. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50177. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50178. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50179. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50180. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50181. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50182. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50183. }
  50184. };
  50185. ParticleSystem.prototype._getEffect = function () {
  50186. if (this._customEffect) {
  50187. return this._customEffect;
  50188. }
  50189. ;
  50190. var defines = [];
  50191. if (this._scene.clipPlane) {
  50192. defines.push("#define CLIPPLANE");
  50193. }
  50194. if (this._isAnimationSheetEnabled) {
  50195. defines.push("#define ANIMATESHEET");
  50196. }
  50197. // Effect
  50198. var join = defines.join("\n");
  50199. if (this._cachedDefines !== join) {
  50200. this._cachedDefines = join;
  50201. var attributesNamesOrOptions;
  50202. var effectCreationOption;
  50203. if (this._isAnimationSheetEnabled) {
  50204. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50205. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50206. }
  50207. else {
  50208. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50209. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50210. }
  50211. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50212. }
  50213. return this._effect;
  50214. };
  50215. /**
  50216. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50217. */
  50218. ParticleSystem.prototype.animate = function () {
  50219. if (!this._started)
  50220. return;
  50221. var effect = this._getEffect();
  50222. // Check
  50223. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50224. return;
  50225. if (this._currentRenderId === this._scene.getRenderId()) {
  50226. return;
  50227. }
  50228. this._currentRenderId = this._scene.getRenderId();
  50229. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50230. // determine the number of particles we need to create
  50231. var newParticles;
  50232. if (this.manualEmitCount > -1) {
  50233. newParticles = this.manualEmitCount;
  50234. this._newPartsExcess = 0;
  50235. this.manualEmitCount = 0;
  50236. }
  50237. else {
  50238. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50239. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50240. }
  50241. if (this._newPartsExcess > 1.0) {
  50242. newParticles += this._newPartsExcess >> 0;
  50243. this._newPartsExcess -= this._newPartsExcess >> 0;
  50244. }
  50245. this._alive = false;
  50246. if (!this._stopped) {
  50247. this._actualFrame += this._scaledUpdateSpeed;
  50248. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50249. this.stop();
  50250. }
  50251. else {
  50252. newParticles = 0;
  50253. }
  50254. this._update(newParticles);
  50255. // Stopped?
  50256. if (this._stopped) {
  50257. if (!this._alive) {
  50258. this._started = false;
  50259. if (this.onAnimationEnd) {
  50260. this.onAnimationEnd();
  50261. }
  50262. if (this.disposeOnStop) {
  50263. this._scene._toBeDisposed.push(this);
  50264. }
  50265. }
  50266. }
  50267. // Animation sheet
  50268. if (this._isAnimationSheetEnabled) {
  50269. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50270. }
  50271. else {
  50272. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50273. }
  50274. // Update VBO
  50275. var offset = 0;
  50276. for (var index = 0; index < this._particles.length; index++) {
  50277. var particle = this._particles[index];
  50278. this._appendParticleVertexes(offset, particle);
  50279. offset += 4;
  50280. }
  50281. if (this._vertexBuffer) {
  50282. this._vertexBuffer.update(this._vertexData);
  50283. }
  50284. };
  50285. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50286. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50287. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50288. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50289. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50290. };
  50291. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50292. this._appendParticleVertex(offset++, particle, 0, 0);
  50293. this._appendParticleVertex(offset++, particle, 1, 0);
  50294. this._appendParticleVertex(offset++, particle, 1, 1);
  50295. this._appendParticleVertex(offset++, particle, 0, 1);
  50296. };
  50297. /**
  50298. * Rebuilds the particle system.
  50299. */
  50300. ParticleSystem.prototype.rebuild = function () {
  50301. this._createIndexBuffer();
  50302. if (this._vertexBuffer) {
  50303. this._vertexBuffer._rebuild();
  50304. }
  50305. };
  50306. /**
  50307. * Renders the particle system in its current state.
  50308. * @returns the current number of particles.
  50309. */
  50310. ParticleSystem.prototype.render = function () {
  50311. var effect = this._getEffect();
  50312. // Check
  50313. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50314. return 0;
  50315. var engine = this._scene.getEngine();
  50316. // Render
  50317. engine.enableEffect(effect);
  50318. engine.setState(false);
  50319. var viewMatrix = this._scene.getViewMatrix();
  50320. effect.setTexture("diffuseSampler", this.particleTexture);
  50321. effect.setMatrix("view", viewMatrix);
  50322. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50323. if (this._isAnimationSheetEnabled) {
  50324. var baseSize = this.particleTexture.getBaseSize();
  50325. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50326. }
  50327. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50328. if (this._scene.clipPlane) {
  50329. var clipPlane = this._scene.clipPlane;
  50330. var invView = viewMatrix.clone();
  50331. invView.invert();
  50332. effect.setMatrix("invView", invView);
  50333. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50334. }
  50335. // VBOs
  50336. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50337. // Draw order
  50338. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50339. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50340. }
  50341. else {
  50342. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50343. }
  50344. if (this.forceDepthWrite) {
  50345. engine.setDepthWrite(true);
  50346. }
  50347. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50348. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50349. return this._particles.length;
  50350. };
  50351. /**
  50352. * Disposes the particle system and free the associated resources.
  50353. */
  50354. ParticleSystem.prototype.dispose = function () {
  50355. if (this._vertexBuffer) {
  50356. this._vertexBuffer.dispose();
  50357. this._vertexBuffer = null;
  50358. }
  50359. if (this._indexBuffer) {
  50360. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50361. this._indexBuffer = null;
  50362. }
  50363. if (this.particleTexture) {
  50364. this.particleTexture.dispose();
  50365. this.particleTexture = null;
  50366. }
  50367. // Remove from scene
  50368. var index = this._scene.particleSystems.indexOf(this);
  50369. if (index > -1) {
  50370. this._scene.particleSystems.splice(index, 1);
  50371. }
  50372. // Callback
  50373. this.onDisposeObservable.notifyObservers(this);
  50374. this.onDisposeObservable.clear();
  50375. };
  50376. /**
  50377. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50378. * @param radius The radius of the sphere to emit from
  50379. * @returns the emitter
  50380. */
  50381. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50382. if (radius === void 0) { radius = 1; }
  50383. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50384. this.particleEmitterType = particleEmitter;
  50385. return particleEmitter;
  50386. };
  50387. /**
  50388. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50389. * @param radius The radius of the sphere to emit from
  50390. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50391. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50392. * @returns the emitter
  50393. */
  50394. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50395. if (radius === void 0) { radius = 1; }
  50396. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50397. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50398. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50399. this.particleEmitterType = particleEmitter;
  50400. return particleEmitter;
  50401. };
  50402. /**
  50403. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50404. * @param radius The radius of the cone to emit from
  50405. * @param angle The base angle of the cone
  50406. * @returns the emitter
  50407. */
  50408. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50409. if (radius === void 0) { radius = 1; }
  50410. if (angle === void 0) { angle = Math.PI / 4; }
  50411. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50412. this.particleEmitterType = particleEmitter;
  50413. return particleEmitter;
  50414. };
  50415. // 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.
  50416. /**
  50417. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50418. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50419. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50420. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50421. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50422. * @returns the emitter
  50423. */
  50424. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50425. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50426. this.direction1 = direction1;
  50427. this.direction2 = direction2;
  50428. this.minEmitBox = minEmitBox;
  50429. this.maxEmitBox = maxEmitBox;
  50430. this.particleEmitterType = particleEmitter;
  50431. return particleEmitter;
  50432. };
  50433. /**
  50434. * Clones the particle system.
  50435. * @param name The name of the cloned object
  50436. * @param newEmitter The new emitter to use
  50437. * @returns the cloned particle system
  50438. */
  50439. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50440. var custom = null;
  50441. var program = null;
  50442. if (this.customShader != null) {
  50443. program = this.customShader;
  50444. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50445. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50446. }
  50447. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50448. result.customShader = program;
  50449. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50450. if (newEmitter === undefined) {
  50451. newEmitter = this.emitter;
  50452. }
  50453. result.emitter = newEmitter;
  50454. if (this.particleTexture) {
  50455. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50456. }
  50457. if (!this.preventAutoStart) {
  50458. result.start();
  50459. }
  50460. return result;
  50461. };
  50462. /**
  50463. * Serializes the particle system to a JSON object.
  50464. * @returns the JSON object
  50465. */
  50466. ParticleSystem.prototype.serialize = function () {
  50467. var serializationObject = {};
  50468. serializationObject.name = this.name;
  50469. serializationObject.id = this.id;
  50470. // Emitter
  50471. if (this.emitter.position) {
  50472. var emitterMesh = this.emitter;
  50473. serializationObject.emitterId = emitterMesh.id;
  50474. }
  50475. else {
  50476. var emitterPosition = this.emitter;
  50477. serializationObject.emitter = emitterPosition.asArray();
  50478. }
  50479. serializationObject.capacity = this.getCapacity();
  50480. if (this.particleTexture) {
  50481. serializationObject.textureName = this.particleTexture.name;
  50482. }
  50483. // Animations
  50484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50485. // Particle system
  50486. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50487. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50488. serializationObject.minSize = this.minSize;
  50489. serializationObject.maxSize = this.maxSize;
  50490. serializationObject.minEmitPower = this.minEmitPower;
  50491. serializationObject.maxEmitPower = this.maxEmitPower;
  50492. serializationObject.minLifeTime = this.minLifeTime;
  50493. serializationObject.maxLifeTime = this.maxLifeTime;
  50494. serializationObject.emitRate = this.emitRate;
  50495. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50496. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50497. serializationObject.gravity = this.gravity.asArray();
  50498. serializationObject.direction1 = this.direction1.asArray();
  50499. serializationObject.direction2 = this.direction2.asArray();
  50500. serializationObject.color1 = this.color1.asArray();
  50501. serializationObject.color2 = this.color2.asArray();
  50502. serializationObject.colorDead = this.colorDead.asArray();
  50503. serializationObject.updateSpeed = this.updateSpeed;
  50504. serializationObject.targetStopDuration = this.targetStopDuration;
  50505. serializationObject.textureMask = this.textureMask.asArray();
  50506. serializationObject.blendMode = this.blendMode;
  50507. serializationObject.customShader = this.customShader;
  50508. serializationObject.preventAutoStart = this.preventAutoStart;
  50509. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50510. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50511. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50512. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50513. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50514. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50515. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50516. return serializationObject;
  50517. };
  50518. /**
  50519. * Parses a JSON object to create a particle system.
  50520. * @param parsedParticleSystem The JSON object to parse
  50521. * @param scene The scene to create the particle system in
  50522. * @param rootUrl The root url to use to load external dependencies like texture
  50523. * @returns the Parsed particle system
  50524. */
  50525. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50526. var name = parsedParticleSystem.name;
  50527. var custom = null;
  50528. var program = null;
  50529. if (parsedParticleSystem.customShader) {
  50530. program = parsedParticleSystem.customShader;
  50531. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50532. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50533. }
  50534. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50535. particleSystem.customShader = program;
  50536. if (parsedParticleSystem.id) {
  50537. particleSystem.id = parsedParticleSystem.id;
  50538. }
  50539. // Auto start
  50540. if (parsedParticleSystem.preventAutoStart) {
  50541. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50542. }
  50543. // Texture
  50544. if (parsedParticleSystem.textureName) {
  50545. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50546. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50547. }
  50548. // Emitter
  50549. if (parsedParticleSystem.emitterId) {
  50550. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50551. }
  50552. else {
  50553. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50554. }
  50555. // Animations
  50556. if (parsedParticleSystem.animations) {
  50557. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50558. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50559. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50560. }
  50561. }
  50562. if (parsedParticleSystem.autoAnimate) {
  50563. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50564. }
  50565. // Particle system
  50566. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50567. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50568. particleSystem.minSize = parsedParticleSystem.minSize;
  50569. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50570. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50571. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50572. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50573. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50574. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50575. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50576. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50577. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50578. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50579. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50580. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50581. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50582. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50583. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50584. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50585. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50586. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50587. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50588. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50589. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50590. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50591. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50592. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50593. if (!particleSystem.preventAutoStart) {
  50594. particleSystem.start();
  50595. }
  50596. return particleSystem;
  50597. };
  50598. /**
  50599. * Source color is added to the destination color without alpha affecting the result.
  50600. */
  50601. ParticleSystem.BLENDMODE_ONEONE = 0;
  50602. /**
  50603. * Blend current color and particle color using particle’s alpha.
  50604. */
  50605. ParticleSystem.BLENDMODE_STANDARD = 1;
  50606. return ParticleSystem;
  50607. }());
  50608. BABYLON.ParticleSystem = ParticleSystem;
  50609. })(BABYLON || (BABYLON = {}));
  50610. //# sourceMappingURL=babylon.particleSystem.js.map
  50611. var BABYLON;
  50612. (function (BABYLON) {
  50613. /**
  50614. * Particle emitter emitting particles from the inside of a box.
  50615. * It emits the particles randomly between 2 given directions.
  50616. */
  50617. var BoxParticleEmitter = /** @class */ (function () {
  50618. // to be updated like the rest of emitters when breaking changes.
  50619. // all property should be come public variables and passed through constructor.
  50620. /**
  50621. * Creates a new instance of @see BoxParticleEmitter
  50622. * @param _particleSystem the particle system associated with the emitter
  50623. */
  50624. function BoxParticleEmitter(_particleSystem) {
  50625. this._particleSystem = _particleSystem;
  50626. }
  50627. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50628. /**
  50629. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50630. */
  50631. get: function () {
  50632. return this._particleSystem.direction1;
  50633. },
  50634. /**
  50635. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50636. */
  50637. set: function (value) {
  50638. this._particleSystem.direction1 = value;
  50639. },
  50640. enumerable: true,
  50641. configurable: true
  50642. });
  50643. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50644. /**
  50645. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50646. */
  50647. get: function () {
  50648. return this._particleSystem.direction2;
  50649. },
  50650. /**
  50651. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50652. */
  50653. set: function (value) {
  50654. this._particleSystem.direction2 = value;
  50655. },
  50656. enumerable: true,
  50657. configurable: true
  50658. });
  50659. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50660. /**
  50661. * 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.
  50662. */
  50663. get: function () {
  50664. return this._particleSystem.minEmitBox;
  50665. },
  50666. /**
  50667. * 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.
  50668. */
  50669. set: function (value) {
  50670. this._particleSystem.minEmitBox = value;
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50676. /**
  50677. * 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.
  50678. */
  50679. get: function () {
  50680. return this._particleSystem.maxEmitBox;
  50681. },
  50682. /**
  50683. * 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.
  50684. */
  50685. set: function (value) {
  50686. this._particleSystem.maxEmitBox = value;
  50687. },
  50688. enumerable: true,
  50689. configurable: true
  50690. });
  50691. /**
  50692. * Called by the particle System when the direction is computed for the created particle.
  50693. * @param emitPower is the power of the particle (speed)
  50694. * @param worldMatrix is the world matrix of the particle system
  50695. * @param directionToUpdate is the direction vector to update with the result
  50696. * @param particle is the particle we are computed the direction for
  50697. */
  50698. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50699. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50700. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50701. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50702. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50703. };
  50704. /**
  50705. * Called by the particle System when the position is computed for the created particle.
  50706. * @param worldMatrix is the world matrix of the particle system
  50707. * @param positionToUpdate is the position vector to update with the result
  50708. * @param particle is the particle we are computed the position for
  50709. */
  50710. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50711. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50712. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50713. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50714. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50715. };
  50716. /**
  50717. * Clones the current emitter and returns a copy of it
  50718. * @returns the new emitter
  50719. */
  50720. BoxParticleEmitter.prototype.clone = function () {
  50721. var newOne = new BoxParticleEmitter(this._particleSystem);
  50722. BABYLON.Tools.DeepCopy(this, newOne);
  50723. return newOne;
  50724. };
  50725. return BoxParticleEmitter;
  50726. }());
  50727. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50728. })(BABYLON || (BABYLON = {}));
  50729. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50730. var BABYLON;
  50731. (function (BABYLON) {
  50732. /**
  50733. * Particle emitter emitting particles from the inside of a cone.
  50734. * It emits the particles alongside the cone volume from the base to the particle.
  50735. * The emission direction might be randomized.
  50736. */
  50737. var ConeParticleEmitter = /** @class */ (function () {
  50738. /**
  50739. * Creates a new instance of @see ConeParticleEmitter
  50740. * @param radius the radius of the emission cone
  50741. * @param angles the cone base angle
  50742. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50743. */
  50744. function ConeParticleEmitter(radius,
  50745. /**
  50746. * The radius of the emission cone.
  50747. */
  50748. angle,
  50749. /**
  50750. * The cone base angle.
  50751. */
  50752. directionRandomizer) {
  50753. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50754. this.angle = angle;
  50755. this.directionRandomizer = directionRandomizer;
  50756. this.radius = radius;
  50757. }
  50758. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50759. /**
  50760. * Gets the radius of the emission cone.
  50761. */
  50762. get: function () {
  50763. return this._radius;
  50764. },
  50765. /**
  50766. * Sets the radius of the emission cone.
  50767. */
  50768. set: function (value) {
  50769. this._radius = value;
  50770. if (this.angle !== 0) {
  50771. this._height = value / Math.tan(this.angle / 2);
  50772. }
  50773. else {
  50774. this._height = 1;
  50775. }
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. /**
  50781. * Called by the particle System when the direction is computed for the created particle.
  50782. * @param emitPower is the power of the particle (speed)
  50783. * @param worldMatrix is the world matrix of the particle system
  50784. * @param directionToUpdate is the direction vector to update with the result
  50785. * @param particle is the particle we are computed the direction for
  50786. */
  50787. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50788. if (this.angle === 0) {
  50789. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50790. }
  50791. else {
  50792. // measure the direction Vector from the emitter to the particle.
  50793. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50794. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50795. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50796. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50797. direction.x += randX;
  50798. direction.y += randY;
  50799. direction.z += randZ;
  50800. direction.normalize();
  50801. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50802. }
  50803. };
  50804. /**
  50805. * Called by the particle System when the position is computed for the created particle.
  50806. * @param worldMatrix is the world matrix of the particle system
  50807. * @param positionToUpdate is the position vector to update with the result
  50808. * @param particle is the particle we are computed the position for
  50809. */
  50810. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50811. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50812. var h = BABYLON.Scalar.RandomRange(0, 1);
  50813. // Better distribution in a cone at normal angles.
  50814. h = 1 - h * h;
  50815. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50816. radius = radius * h / this._height;
  50817. var randX = radius * Math.sin(s);
  50818. var randZ = radius * Math.cos(s);
  50819. var randY = h;
  50820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50821. };
  50822. /**
  50823. * Clones the current emitter and returns a copy of it
  50824. * @returns the new emitter
  50825. */
  50826. ConeParticleEmitter.prototype.clone = function () {
  50827. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50828. BABYLON.Tools.DeepCopy(this, newOne);
  50829. return newOne;
  50830. };
  50831. return ConeParticleEmitter;
  50832. }());
  50833. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50834. })(BABYLON || (BABYLON = {}));
  50835. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50836. var BABYLON;
  50837. (function (BABYLON) {
  50838. /**
  50839. * Particle emitter emitting particles from the inside of a sphere.
  50840. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50841. */
  50842. var SphereParticleEmitter = /** @class */ (function () {
  50843. /**
  50844. * Creates a new instance of @see SphereParticleEmitter
  50845. * @param radius the radius of the emission sphere
  50846. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50847. */
  50848. function SphereParticleEmitter(
  50849. /**
  50850. * The radius of the emission sphere.
  50851. */
  50852. radius,
  50853. /**
  50854. * How much to randomize the particle direction [0-1].
  50855. */
  50856. directionRandomizer) {
  50857. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50858. this.radius = radius;
  50859. this.directionRandomizer = directionRandomizer;
  50860. }
  50861. /**
  50862. * Called by the particle System when the direction is computed for the created particle.
  50863. * @param emitPower is the power of the particle (speed)
  50864. * @param worldMatrix is the world matrix of the particle system
  50865. * @param directionToUpdate is the direction vector to update with the result
  50866. * @param particle is the particle we are computed the direction for
  50867. */
  50868. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50869. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50870. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50871. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50872. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50873. direction.x += randX;
  50874. direction.y += randY;
  50875. direction.z += randZ;
  50876. direction.normalize();
  50877. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50878. };
  50879. /**
  50880. * Called by the particle System when the position is computed for the created particle.
  50881. * @param worldMatrix is the world matrix of the particle system
  50882. * @param positionToUpdate is the position vector to update with the result
  50883. * @param particle is the particle we are computed the position for
  50884. */
  50885. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50886. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50887. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50888. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50889. var randY = this.radius * Math.cos(theta);
  50890. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  50891. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50892. };
  50893. /**
  50894. * Clones the current emitter and returns a copy of it
  50895. * @returns the new emitter
  50896. */
  50897. SphereParticleEmitter.prototype.clone = function () {
  50898. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  50899. BABYLON.Tools.DeepCopy(this, newOne);
  50900. return newOne;
  50901. };
  50902. return SphereParticleEmitter;
  50903. }());
  50904. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  50905. /**
  50906. * Particle emitter emitting particles from the inside of a sphere.
  50907. * It emits the particles randomly between two vectors.
  50908. */
  50909. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  50910. __extends(SphereDirectedParticleEmitter, _super);
  50911. /**
  50912. * Creates a new instance of @see SphereDirectedParticleEmitter
  50913. * @param radius the radius of the emission sphere
  50914. * @param direction1 the min limit of the emission direction
  50915. * @param direction2 the max limit of the emission direction
  50916. */
  50917. function SphereDirectedParticleEmitter(radius,
  50918. /**
  50919. * The min limit of the emission direction.
  50920. */
  50921. direction1,
  50922. /**
  50923. * The max limit of the emission direction.
  50924. */
  50925. direction2) {
  50926. var _this = _super.call(this, radius) || this;
  50927. _this.direction1 = direction1;
  50928. _this.direction2 = direction2;
  50929. return _this;
  50930. }
  50931. /**
  50932. * Called by the particle System when the direction is computed for the created particle.
  50933. * @param emitPower is the power of the particle (speed)
  50934. * @param worldMatrix is the world matrix of the particle system
  50935. * @param directionToUpdate is the direction vector to update with the result
  50936. * @param particle is the particle we are computed the direction for
  50937. */
  50938. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50939. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50940. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50941. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50942. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50943. };
  50944. /**
  50945. * Clones the current emitter and returns a copy of it
  50946. * @returns the new emitter
  50947. */
  50948. SphereDirectedParticleEmitter.prototype.clone = function () {
  50949. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  50950. BABYLON.Tools.DeepCopy(this, newOne);
  50951. return newOne;
  50952. };
  50953. return SphereDirectedParticleEmitter;
  50954. }(SphereParticleEmitter));
  50955. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  50956. })(BABYLON || (BABYLON = {}));
  50957. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  50958. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  50959. var BABYLON;
  50960. (function (BABYLON) {
  50961. /**
  50962. * Represents one particle of a solid particle system.
  50963. * @see SolidParticleSystem
  50964. */
  50965. var SolidParticle = /** @class */ (function () {
  50966. /**
  50967. * Creates a Solid Particle object.
  50968. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  50969. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  50970. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  50971. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  50972. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  50973. * @param shapeId (integer) is the model shape identifier in the SPS.
  50974. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  50975. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  50976. */
  50977. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  50978. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  50979. /**
  50980. * particle global index
  50981. */
  50982. this.idx = 0;
  50983. /**
  50984. * The color of the particle
  50985. */
  50986. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50987. /**
  50988. * The world space position of the particle.
  50989. */
  50990. this.position = BABYLON.Vector3.Zero();
  50991. /**
  50992. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  50993. */
  50994. this.rotation = BABYLON.Vector3.Zero();
  50995. /**
  50996. * The scaling of the particle.
  50997. */
  50998. this.scaling = BABYLON.Vector3.One();
  50999. /**
  51000. * The uvs of the particle.
  51001. */
  51002. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51003. /**
  51004. * The current speed of the particle.
  51005. */
  51006. this.velocity = BABYLON.Vector3.Zero();
  51007. /**
  51008. * The pivot point in the particle local space.
  51009. */
  51010. this.pivot = BABYLON.Vector3.Zero();
  51011. /**
  51012. * Must the particle be translated from its pivot point in its local space ?
  51013. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51014. * Default : false
  51015. */
  51016. this.translateFromPivot = false;
  51017. /**
  51018. * Is the particle active or not ?
  51019. */
  51020. this.alive = true;
  51021. /**
  51022. * Is the particle visible or not ?
  51023. */
  51024. this.isVisible = true;
  51025. /**
  51026. * Index of this particle in the global "positions" array (Internal use)
  51027. */
  51028. this._pos = 0;
  51029. /**
  51030. * Index of this particle in the global "indices" array (Internal use)
  51031. */
  51032. this._ind = 0;
  51033. /**
  51034. * ModelShape id of this particle
  51035. */
  51036. this.shapeId = 0;
  51037. /**
  51038. * Index of the particle in its shape id (Internal use)
  51039. */
  51040. this.idxInShape = 0;
  51041. /**
  51042. * Still set as invisible in order to skip useless computations (Internal use)
  51043. */
  51044. this._stillInvisible = false;
  51045. /**
  51046. * Last computed particle rotation matrix
  51047. */
  51048. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51049. this.idx = particleIndex;
  51050. this._pos = positionIndex;
  51051. this._ind = indiceIndex;
  51052. this._model = model;
  51053. this.shapeId = shapeId;
  51054. this.idxInShape = idxInShape;
  51055. this._sps = sps;
  51056. if (modelBoundingInfo) {
  51057. this._modelBoundingInfo = modelBoundingInfo;
  51058. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51059. }
  51060. }
  51061. Object.defineProperty(SolidParticle.prototype, "scale", {
  51062. /**
  51063. * Legacy support, changed scale to scaling
  51064. */
  51065. get: function () {
  51066. return this.scaling;
  51067. },
  51068. /**
  51069. * Legacy support, changed scale to scaling
  51070. */
  51071. set: function (scale) {
  51072. this.scaling = scale;
  51073. },
  51074. enumerable: true,
  51075. configurable: true
  51076. });
  51077. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51078. /**
  51079. * Legacy support, changed quaternion to rotationQuaternion
  51080. */
  51081. get: function () {
  51082. return this.rotationQuaternion;
  51083. },
  51084. /**
  51085. * Legacy support, changed quaternion to rotationQuaternion
  51086. */
  51087. set: function (q) {
  51088. this.rotationQuaternion = q;
  51089. },
  51090. enumerable: true,
  51091. configurable: true
  51092. });
  51093. /**
  51094. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51095. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51096. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51097. * @returns true if it intersects
  51098. */
  51099. SolidParticle.prototype.intersectsMesh = function (target) {
  51100. if (!this._boundingInfo || !target._boundingInfo) {
  51101. return false;
  51102. }
  51103. if (this._sps._bSphereOnly) {
  51104. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51105. }
  51106. return this._boundingInfo.intersects(target._boundingInfo, false);
  51107. };
  51108. return SolidParticle;
  51109. }());
  51110. BABYLON.SolidParticle = SolidParticle;
  51111. /**
  51112. * Represents the shape of the model used by one particle of a solid particle system.
  51113. * SPS internal tool, don't use it manually.
  51114. * @see SolidParticleSystem
  51115. */
  51116. var ModelShape = /** @class */ (function () {
  51117. /**
  51118. * 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.
  51119. * SPS internal tool, don't use it manually.
  51120. * @ignore
  51121. */
  51122. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51123. /**
  51124. * length of the shape in the model indices array (internal use)
  51125. */
  51126. this._indicesLength = 0;
  51127. this.shapeID = id;
  51128. this._shape = shape;
  51129. this._indicesLength = indicesLength;
  51130. this._shapeUV = shapeUV;
  51131. this._positionFunction = posFunction;
  51132. this._vertexFunction = vtxFunction;
  51133. }
  51134. return ModelShape;
  51135. }());
  51136. BABYLON.ModelShape = ModelShape;
  51137. /**
  51138. * Represents a Depth Sorted Particle in the solid particle system.
  51139. * @see SolidParticleSystem
  51140. */
  51141. var DepthSortedParticle = /** @class */ (function () {
  51142. function DepthSortedParticle() {
  51143. /**
  51144. * Index of the particle in the "indices" array
  51145. */
  51146. this.ind = 0;
  51147. /**
  51148. * Length of the particle shape in the "indices" array
  51149. */
  51150. this.indicesLength = 0;
  51151. /**
  51152. * Squared distance from the particle to the camera
  51153. */
  51154. this.sqDistance = 0.0;
  51155. }
  51156. return DepthSortedParticle;
  51157. }());
  51158. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51159. })(BABYLON || (BABYLON = {}));
  51160. //# sourceMappingURL=babylon.solidParticle.js.map
  51161. var BABYLON;
  51162. (function (BABYLON) {
  51163. /**
  51164. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51165. *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.
  51166. * The SPS is also a particle system. It provides some methods to manage the particles.
  51167. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51168. *
  51169. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51170. */
  51171. var SolidParticleSystem = /** @class */ (function () {
  51172. /**
  51173. * Creates a SPS (Solid Particle System) object.
  51174. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51175. * @param scene (Scene) is the scene in which the SPS is added.
  51176. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51177. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51178. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51179. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51180. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51181. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51182. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51183. */
  51184. function SolidParticleSystem(name, scene, options) {
  51185. /**
  51186. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51187. * Example : var p = SPS.particles[i];
  51188. */
  51189. this.particles = new Array();
  51190. /**
  51191. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51192. */
  51193. this.nbParticles = 0;
  51194. /**
  51195. * If the particles must ever face the camera (default false). Useful for planar particles.
  51196. */
  51197. this.billboard = false;
  51198. /**
  51199. * Recompute normals when adding a shape
  51200. */
  51201. this.recomputeNormals = true;
  51202. /**
  51203. * This a counter ofr your own usage. It's not set by any SPS functions.
  51204. */
  51205. this.counter = 0;
  51206. /**
  51207. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51208. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51209. */
  51210. this.vars = {};
  51211. /**
  51212. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51213. */
  51214. this._bSphereOnly = false;
  51215. /**
  51216. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51217. */
  51218. this._bSphereRadiusFactor = 1.0;
  51219. this._positions = new Array();
  51220. this._indices = new Array();
  51221. this._normals = new Array();
  51222. this._colors = new Array();
  51223. this._uvs = new Array();
  51224. this._index = 0; // indices index
  51225. this._updatable = true;
  51226. this._pickable = false;
  51227. this._isVisibilityBoxLocked = false;
  51228. this._alwaysVisible = false;
  51229. this._depthSort = false;
  51230. this._shapeCounter = 0;
  51231. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51232. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51233. this._computeParticleColor = true;
  51234. this._computeParticleTexture = true;
  51235. this._computeParticleRotation = true;
  51236. this._computeParticleVertex = false;
  51237. this._computeBoundingBox = false;
  51238. this._depthSortParticles = true;
  51239. this._cam_axisZ = BABYLON.Vector3.Zero();
  51240. this._cam_axisY = BABYLON.Vector3.Zero();
  51241. this._cam_axisX = BABYLON.Vector3.Zero();
  51242. this._axisZ = BABYLON.Axis.Z;
  51243. this._camDir = BABYLON.Vector3.Zero();
  51244. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51245. this._rotMatrix = new BABYLON.Matrix();
  51246. this._invertMatrix = new BABYLON.Matrix();
  51247. this._rotated = BABYLON.Vector3.Zero();
  51248. this._quaternion = new BABYLON.Quaternion();
  51249. this._vertex = BABYLON.Vector3.Zero();
  51250. this._normal = BABYLON.Vector3.Zero();
  51251. this._yaw = 0.0;
  51252. this._pitch = 0.0;
  51253. this._roll = 0.0;
  51254. this._halfroll = 0.0;
  51255. this._halfpitch = 0.0;
  51256. this._halfyaw = 0.0;
  51257. this._sinRoll = 0.0;
  51258. this._cosRoll = 0.0;
  51259. this._sinPitch = 0.0;
  51260. this._cosPitch = 0.0;
  51261. this._sinYaw = 0.0;
  51262. this._cosYaw = 0.0;
  51263. this._mustUnrotateFixedNormals = false;
  51264. this._minimum = BABYLON.Vector3.Zero();
  51265. this._maximum = BABYLON.Vector3.Zero();
  51266. this._minBbox = BABYLON.Vector3.Zero();
  51267. this._maxBbox = BABYLON.Vector3.Zero();
  51268. this._particlesIntersect = false;
  51269. this._depthSortFunction = function (p1, p2) {
  51270. return (p2.sqDistance - p1.sqDistance);
  51271. };
  51272. this._needs32Bits = false;
  51273. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51274. this.name = name;
  51275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51276. this._camera = scene.activeCamera;
  51277. this._pickable = options ? options.isPickable : false;
  51278. this._depthSort = options ? options.enableDepthSort : false;
  51279. this._particlesIntersect = options ? options.particleIntersection : false;
  51280. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51281. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51282. if (options && options.updatable) {
  51283. this._updatable = options.updatable;
  51284. }
  51285. else {
  51286. this._updatable = true;
  51287. }
  51288. if (this._pickable) {
  51289. this.pickedParticles = [];
  51290. }
  51291. if (this._depthSort) {
  51292. this.depthSortedParticles = [];
  51293. }
  51294. }
  51295. /**
  51296. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51297. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51298. * @returns the created mesh
  51299. */
  51300. SolidParticleSystem.prototype.buildMesh = function () {
  51301. if (this.nbParticles === 0) {
  51302. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51303. this.addShape(triangle, 1);
  51304. triangle.dispose();
  51305. }
  51306. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51307. this._positions32 = new Float32Array(this._positions);
  51308. this._uvs32 = new Float32Array(this._uvs);
  51309. this._colors32 = new Float32Array(this._colors);
  51310. if (this.recomputeNormals) {
  51311. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51312. }
  51313. this._normals32 = new Float32Array(this._normals);
  51314. this._fixedNormal32 = new Float32Array(this._normals);
  51315. if (this._mustUnrotateFixedNormals) {
  51316. this._unrotateFixedNormals();
  51317. }
  51318. var vertexData = new BABYLON.VertexData();
  51319. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51320. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51321. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51322. if (this._uvs32) {
  51323. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51324. ;
  51325. }
  51326. if (this._colors32) {
  51327. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51328. }
  51329. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51330. vertexData.applyToMesh(mesh, this._updatable);
  51331. this.mesh = mesh;
  51332. this.mesh.isPickable = this._pickable;
  51333. // free memory
  51334. if (!this._depthSort) {
  51335. this._indices = null;
  51336. }
  51337. this._positions = null;
  51338. this._normals = null;
  51339. this._uvs = null;
  51340. this._colors = null;
  51341. if (!this._updatable) {
  51342. this.particles.length = 0;
  51343. }
  51344. return mesh;
  51345. };
  51346. /**
  51347. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51348. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51349. * Thus the particles generated from `digest()` have their property `position` set yet.
  51350. * @param mesh ( Mesh ) is the mesh to be digested
  51351. * @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
  51352. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51353. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51354. * @returns the current SPS
  51355. */
  51356. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51357. var size = (options && options.facetNb) || 1;
  51358. var number = (options && options.number) || 0;
  51359. var delta = (options && options.delta) || 0;
  51360. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51361. var meshInd = mesh.getIndices();
  51362. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51363. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51364. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51365. var f = 0; // facet counter
  51366. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51367. // compute size from number
  51368. if (number) {
  51369. number = (number > totalFacets) ? totalFacets : number;
  51370. size = Math.round(totalFacets / number);
  51371. delta = 0;
  51372. }
  51373. else {
  51374. size = (size > totalFacets) ? totalFacets : size;
  51375. }
  51376. var facetPos = []; // submesh positions
  51377. var facetInd = []; // submesh indices
  51378. var facetUV = []; // submesh UV
  51379. var facetCol = []; // submesh colors
  51380. var barycenter = BABYLON.Vector3.Zero();
  51381. var sizeO = size;
  51382. while (f < totalFacets) {
  51383. size = sizeO + Math.floor((1 + delta) * Math.random());
  51384. if (f > totalFacets - size) {
  51385. size = totalFacets - f;
  51386. }
  51387. // reset temp arrays
  51388. facetPos.length = 0;
  51389. facetInd.length = 0;
  51390. facetUV.length = 0;
  51391. facetCol.length = 0;
  51392. // iterate over "size" facets
  51393. var fi = 0;
  51394. for (var j = f * 3; j < (f + size) * 3; j++) {
  51395. facetInd.push(fi);
  51396. var i = meshInd[j];
  51397. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51398. if (meshUV) {
  51399. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51400. }
  51401. if (meshCol) {
  51402. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51403. }
  51404. fi++;
  51405. }
  51406. // create a model shape for each single particle
  51407. var idx = this.nbParticles;
  51408. var shape = this._posToShape(facetPos);
  51409. var shapeUV = this._uvsToShapeUV(facetUV);
  51410. // compute the barycenter of the shape
  51411. var v;
  51412. for (v = 0; v < shape.length; v++) {
  51413. barycenter.addInPlace(shape[v]);
  51414. }
  51415. barycenter.scaleInPlace(1 / shape.length);
  51416. // shift the shape from its barycenter to the origin
  51417. for (v = 0; v < shape.length; v++) {
  51418. shape[v].subtractInPlace(barycenter);
  51419. }
  51420. var bInfo;
  51421. if (this._particlesIntersect) {
  51422. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51423. }
  51424. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51425. // add the particle in the SPS
  51426. var currentPos = this._positions.length;
  51427. var currentInd = this._indices.length;
  51428. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51429. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51430. // initialize the particle position
  51431. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51432. this._index += shape.length;
  51433. idx++;
  51434. this.nbParticles++;
  51435. this._shapeCounter++;
  51436. f += size;
  51437. }
  51438. return this;
  51439. };
  51440. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51441. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51442. var index = 0;
  51443. var idx = 0;
  51444. for (var p = 0; p < this.particles.length; p++) {
  51445. this._particle = this.particles[p];
  51446. this._shape = this._particle._model._shape;
  51447. if (this._particle.rotationQuaternion) {
  51448. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51449. }
  51450. else {
  51451. this._yaw = this._particle.rotation.y;
  51452. this._pitch = this._particle.rotation.x;
  51453. this._roll = this._particle.rotation.z;
  51454. this._quaternionRotationYPR();
  51455. }
  51456. this._quaternionToRotationMatrix();
  51457. this._rotMatrix.invertToRef(this._invertMatrix);
  51458. for (var pt = 0; pt < this._shape.length; pt++) {
  51459. idx = index + pt * 3;
  51460. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51461. this._fixedNormal32[idx] = this._normal.x;
  51462. this._fixedNormal32[idx + 1] = this._normal.y;
  51463. this._fixedNormal32[idx + 2] = this._normal.z;
  51464. }
  51465. index = idx + 3;
  51466. }
  51467. };
  51468. //reset copy
  51469. SolidParticleSystem.prototype._resetCopy = function () {
  51470. this._copy.position.x = 0;
  51471. this._copy.position.y = 0;
  51472. this._copy.position.z = 0;
  51473. this._copy.rotation.x = 0;
  51474. this._copy.rotation.y = 0;
  51475. this._copy.rotation.z = 0;
  51476. this._copy.rotationQuaternion = null;
  51477. this._copy.scaling.x = 1.0;
  51478. this._copy.scaling.y = 1.0;
  51479. this._copy.scaling.z = 1.0;
  51480. this._copy.uvs.x = 0;
  51481. this._copy.uvs.y = 0;
  51482. this._copy.uvs.z = 1.0;
  51483. this._copy.uvs.w = 1.0;
  51484. this._copy.color = null;
  51485. this._copy.translateFromPivot = false;
  51486. };
  51487. // _meshBuilder : inserts the shape model in the global SPS mesh
  51488. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51489. var i;
  51490. var u = 0;
  51491. var c = 0;
  51492. var n = 0;
  51493. this._resetCopy();
  51494. if (options && options.positionFunction) {
  51495. options.positionFunction(this._copy, idx, idxInShape);
  51496. this._mustUnrotateFixedNormals = true;
  51497. }
  51498. if (this._copy.rotationQuaternion) {
  51499. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51500. }
  51501. else {
  51502. this._yaw = this._copy.rotation.y;
  51503. this._pitch = this._copy.rotation.x;
  51504. this._roll = this._copy.rotation.z;
  51505. this._quaternionRotationYPR();
  51506. }
  51507. this._quaternionToRotationMatrix();
  51508. if (this._copy.translateFromPivot) {
  51509. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51510. }
  51511. else {
  51512. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51513. }
  51514. for (i = 0; i < shape.length; i++) {
  51515. this._vertex.x = shape[i].x;
  51516. this._vertex.y = shape[i].y;
  51517. this._vertex.z = shape[i].z;
  51518. if (options && options.vertexFunction) {
  51519. options.vertexFunction(this._copy, this._vertex, i);
  51520. }
  51521. this._vertex.x *= this._copy.scaling.x;
  51522. this._vertex.y *= this._copy.scaling.y;
  51523. this._vertex.z *= this._copy.scaling.z;
  51524. this._vertex.x -= this._copy.pivot.x;
  51525. this._vertex.y -= this._copy.pivot.y;
  51526. this._vertex.z -= this._copy.pivot.z;
  51527. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51528. this._rotated.addInPlace(this._pivotBackTranslation);
  51529. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51530. if (meshUV) {
  51531. 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);
  51532. u += 2;
  51533. }
  51534. if (this._copy.color) {
  51535. this._color = this._copy.color;
  51536. }
  51537. else if (meshCol && meshCol[c] !== undefined) {
  51538. this._color.r = meshCol[c];
  51539. this._color.g = meshCol[c + 1];
  51540. this._color.b = meshCol[c + 2];
  51541. this._color.a = meshCol[c + 3];
  51542. }
  51543. else {
  51544. this._color.r = 1.0;
  51545. this._color.g = 1.0;
  51546. this._color.b = 1.0;
  51547. this._color.a = 1.0;
  51548. }
  51549. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51550. c += 4;
  51551. if (!this.recomputeNormals && meshNor) {
  51552. this._normal.x = meshNor[n];
  51553. this._normal.y = meshNor[n + 1];
  51554. this._normal.z = meshNor[n + 2];
  51555. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51556. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51557. n += 3;
  51558. }
  51559. }
  51560. for (i = 0; i < meshInd.length; i++) {
  51561. var current_ind = p + meshInd[i];
  51562. indices.push(current_ind);
  51563. if (current_ind > 65535) {
  51564. this._needs32Bits = true;
  51565. }
  51566. }
  51567. if (this._pickable) {
  51568. var nbfaces = meshInd.length / 3;
  51569. for (i = 0; i < nbfaces; i++) {
  51570. this.pickedParticles.push({ idx: idx, faceId: i });
  51571. }
  51572. }
  51573. if (this._depthSort) {
  51574. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51575. }
  51576. return this._copy;
  51577. };
  51578. // returns a shape array from positions array
  51579. SolidParticleSystem.prototype._posToShape = function (positions) {
  51580. var shape = [];
  51581. for (var i = 0; i < positions.length; i += 3) {
  51582. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51583. }
  51584. return shape;
  51585. };
  51586. // returns a shapeUV array from a Vector4 uvs
  51587. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51588. var shapeUV = [];
  51589. if (uvs) {
  51590. for (var i = 0; i < uvs.length; i++)
  51591. shapeUV.push(uvs[i]);
  51592. }
  51593. return shapeUV;
  51594. };
  51595. // adds a new particle object in the particles array
  51596. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51597. if (bInfo === void 0) { bInfo = null; }
  51598. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51599. this.particles.push(sp);
  51600. return sp;
  51601. };
  51602. /**
  51603. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51604. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51605. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51606. * @param nb (positive integer) the number of particles to be created from this model
  51607. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51608. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51609. * @returns the number of shapes in the system
  51610. */
  51611. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51612. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51613. var meshInd = mesh.getIndices();
  51614. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51615. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51616. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51617. var bbInfo;
  51618. if (this._particlesIntersect) {
  51619. bbInfo = mesh.getBoundingInfo();
  51620. }
  51621. var shape = this._posToShape(meshPos);
  51622. var shapeUV = this._uvsToShapeUV(meshUV);
  51623. var posfunc = options ? options.positionFunction : null;
  51624. var vtxfunc = options ? options.vertexFunction : null;
  51625. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51626. // particles
  51627. var sp;
  51628. var currentCopy;
  51629. var idx = this.nbParticles;
  51630. for (var i = 0; i < nb; i++) {
  51631. var currentPos = this._positions.length;
  51632. var currentInd = this._indices.length;
  51633. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51634. if (this._updatable) {
  51635. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51636. sp.position.copyFrom(currentCopy.position);
  51637. sp.rotation.copyFrom(currentCopy.rotation);
  51638. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51639. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51640. }
  51641. if (currentCopy.color && sp.color) {
  51642. sp.color.copyFrom(currentCopy.color);
  51643. }
  51644. sp.scaling.copyFrom(currentCopy.scaling);
  51645. sp.uvs.copyFrom(currentCopy.uvs);
  51646. }
  51647. this._index += shape.length;
  51648. idx++;
  51649. }
  51650. this.nbParticles += nb;
  51651. this._shapeCounter++;
  51652. return this._shapeCounter - 1;
  51653. };
  51654. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51655. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51656. this._resetCopy();
  51657. if (particle._model._positionFunction) {
  51658. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51659. }
  51660. if (this._copy.rotationQuaternion) {
  51661. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51662. }
  51663. else {
  51664. this._yaw = this._copy.rotation.y;
  51665. this._pitch = this._copy.rotation.x;
  51666. this._roll = this._copy.rotation.z;
  51667. this._quaternionRotationYPR();
  51668. }
  51669. this._quaternionToRotationMatrix();
  51670. if (this._copy.translateFromPivot) {
  51671. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51672. }
  51673. else {
  51674. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51675. }
  51676. this._shape = particle._model._shape;
  51677. for (var pt = 0; pt < this._shape.length; pt++) {
  51678. this._vertex.x = this._shape[pt].x;
  51679. this._vertex.y = this._shape[pt].y;
  51680. this._vertex.z = this._shape[pt].z;
  51681. if (particle._model._vertexFunction) {
  51682. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51683. }
  51684. this._vertex.x *= this._copy.scaling.x;
  51685. this._vertex.y *= this._copy.scaling.y;
  51686. this._vertex.z *= this._copy.scaling.z;
  51687. this._vertex.x -= this._copy.pivot.x;
  51688. this._vertex.y -= this._copy.pivot.y;
  51689. this._vertex.z -= this._copy.pivot.z;
  51690. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51691. this._rotated.addInPlace(this._pivotBackTranslation);
  51692. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51693. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51694. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51695. }
  51696. particle.position.x = 0.0;
  51697. particle.position.y = 0.0;
  51698. particle.position.z = 0.0;
  51699. particle.rotation.x = 0.0;
  51700. particle.rotation.y = 0.0;
  51701. particle.rotation.z = 0.0;
  51702. particle.rotationQuaternion = null;
  51703. particle.scaling.x = 1.0;
  51704. particle.scaling.y = 1.0;
  51705. particle.scaling.z = 1.0;
  51706. };
  51707. /**
  51708. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51709. * @returns the SPS.
  51710. */
  51711. SolidParticleSystem.prototype.rebuildMesh = function () {
  51712. for (var p = 0; p < this.particles.length; p++) {
  51713. this._rebuildParticle(this.particles[p]);
  51714. }
  51715. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51716. return this;
  51717. };
  51718. /**
  51719. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51720. * This method calls `updateParticle()` for each particle of the SPS.
  51721. * For an animated SPS, it is usually called within the render loop.
  51722. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51723. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51724. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51725. * @returns the SPS.
  51726. */
  51727. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51728. if (start === void 0) { start = 0; }
  51729. if (end === void 0) { end = this.nbParticles - 1; }
  51730. if (update === void 0) { update = true; }
  51731. if (!this._updatable) {
  51732. return this;
  51733. }
  51734. // custom beforeUpdate
  51735. this.beforeUpdateParticles(start, end, update);
  51736. this._cam_axisX.x = 1.0;
  51737. this._cam_axisX.y = 0.0;
  51738. this._cam_axisX.z = 0.0;
  51739. this._cam_axisY.x = 0.0;
  51740. this._cam_axisY.y = 1.0;
  51741. this._cam_axisY.z = 0.0;
  51742. this._cam_axisZ.x = 0.0;
  51743. this._cam_axisZ.y = 0.0;
  51744. this._cam_axisZ.z = 1.0;
  51745. // cases when the World Matrix is to be computed first
  51746. if (this.billboard || this._depthSort) {
  51747. this.mesh.computeWorldMatrix(true);
  51748. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51749. }
  51750. // if the particles will always face the camera
  51751. if (this.billboard) {
  51752. // compute the camera position and un-rotate it by the current mesh rotation
  51753. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51754. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51755. this._cam_axisZ.normalize();
  51756. // same for camera up vector extracted from the cam view matrix
  51757. var view = this._camera.getViewMatrix(true);
  51758. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51759. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51760. this._cam_axisY.normalize();
  51761. this._cam_axisX.normalize();
  51762. }
  51763. // if depthSort, compute the camera global position in the mesh local system
  51764. if (this._depthSort) {
  51765. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51766. }
  51767. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51768. var idx = 0; // current position index in the global array positions32
  51769. var index = 0; // position start index in the global array positions32 of the current particle
  51770. var colidx = 0; // current color index in the global array colors32
  51771. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51772. var uvidx = 0; // current uv index in the global array uvs32
  51773. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51774. var pt = 0; // current index in the particle model shape
  51775. if (this.mesh.isFacetDataEnabled) {
  51776. this._computeBoundingBox = true;
  51777. }
  51778. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51779. if (this._computeBoundingBox) {
  51780. if (start == 0 && end == this.nbParticles - 1) {
  51781. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51782. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51783. }
  51784. else {
  51785. if (this.mesh._boundingInfo) {
  51786. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51787. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51788. }
  51789. }
  51790. }
  51791. // particle loop
  51792. index = this.particles[start]._pos;
  51793. var vpos = (index / 3) | 0;
  51794. colorIndex = vpos * 4;
  51795. uvIndex = vpos * 2;
  51796. for (var p = start; p <= end; p++) {
  51797. this._particle = this.particles[p];
  51798. this._shape = this._particle._model._shape;
  51799. this._shapeUV = this._particle._model._shapeUV;
  51800. // call to custom user function to update the particle properties
  51801. this.updateParticle(this._particle);
  51802. // camera-particle distance for depth sorting
  51803. if (this._depthSort && this._depthSortParticles) {
  51804. var dsp = this.depthSortedParticles[p];
  51805. dsp.ind = this._particle._ind;
  51806. dsp.indicesLength = this._particle._model._indicesLength;
  51807. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51808. }
  51809. // skip the computations for inactive or already invisible particles
  51810. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51811. // increment indexes for the next particle
  51812. pt = this._shape.length;
  51813. index += pt * 3;
  51814. colorIndex += pt * 4;
  51815. uvIndex += pt * 2;
  51816. continue;
  51817. }
  51818. if (this._particle.isVisible) {
  51819. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51820. // particle rotation matrix
  51821. if (this.billboard) {
  51822. this._particle.rotation.x = 0.0;
  51823. this._particle.rotation.y = 0.0;
  51824. }
  51825. if (this._computeParticleRotation || this.billboard) {
  51826. if (this._particle.rotationQuaternion) {
  51827. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51828. }
  51829. else {
  51830. this._yaw = this._particle.rotation.y;
  51831. this._pitch = this._particle.rotation.x;
  51832. this._roll = this._particle.rotation.z;
  51833. this._quaternionRotationYPR();
  51834. }
  51835. this._quaternionToRotationMatrix();
  51836. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51837. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51838. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51839. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51840. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51841. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51842. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51843. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51844. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51845. }
  51846. if (this._particle.translateFromPivot) {
  51847. this._pivotBackTranslation.x = 0.0;
  51848. this._pivotBackTranslation.y = 0.0;
  51849. this._pivotBackTranslation.z = 0.0;
  51850. }
  51851. else {
  51852. this._pivotBackTranslation.x = this._particle.pivot.x;
  51853. this._pivotBackTranslation.y = this._particle.pivot.y;
  51854. this._pivotBackTranslation.z = this._particle.pivot.z;
  51855. }
  51856. // particle vertex loop
  51857. for (pt = 0; pt < this._shape.length; pt++) {
  51858. idx = index + pt * 3;
  51859. colidx = colorIndex + pt * 4;
  51860. uvidx = uvIndex + pt * 2;
  51861. this._vertex.x = this._shape[pt].x;
  51862. this._vertex.y = this._shape[pt].y;
  51863. this._vertex.z = this._shape[pt].z;
  51864. if (this._computeParticleVertex) {
  51865. this.updateParticleVertex(this._particle, this._vertex, pt);
  51866. }
  51867. // positions
  51868. this._vertex.x *= this._particle.scaling.x;
  51869. this._vertex.y *= this._particle.scaling.y;
  51870. this._vertex.z *= this._particle.scaling.z;
  51871. this._vertex.x -= this._particle.pivot.x;
  51872. this._vertex.y -= this._particle.pivot.y;
  51873. this._vertex.z -= this._particle.pivot.z;
  51874. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51875. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51876. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51877. this._rotated.x += this._pivotBackTranslation.x;
  51878. this._rotated.y += this._pivotBackTranslation.y;
  51879. this._rotated.z += this._pivotBackTranslation.z;
  51880. 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;
  51881. 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;
  51882. 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;
  51883. if (this._computeBoundingBox) {
  51884. if (this._positions32[idx] < this._minimum.x) {
  51885. this._minimum.x = this._positions32[idx];
  51886. }
  51887. if (this._positions32[idx] > this._maximum.x) {
  51888. this._maximum.x = this._positions32[idx];
  51889. }
  51890. if (this._positions32[idx + 1] < this._minimum.y) {
  51891. this._minimum.y = this._positions32[idx + 1];
  51892. }
  51893. if (this._positions32[idx + 1] > this._maximum.y) {
  51894. this._maximum.y = this._positions32[idx + 1];
  51895. }
  51896. if (this._positions32[idx + 2] < this._minimum.z) {
  51897. this._minimum.z = this._positions32[idx + 2];
  51898. }
  51899. if (this._positions32[idx + 2] > this._maximum.z) {
  51900. this._maximum.z = this._positions32[idx + 2];
  51901. }
  51902. }
  51903. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  51904. if (!this._computeParticleVertex) {
  51905. this._normal.x = this._fixedNormal32[idx];
  51906. this._normal.y = this._fixedNormal32[idx + 1];
  51907. this._normal.z = this._fixedNormal32[idx + 2];
  51908. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  51909. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  51910. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  51911. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51912. 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;
  51913. 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;
  51914. }
  51915. if (this._computeParticleColor && this._particle.color) {
  51916. this._colors32[colidx] = this._particle.color.r;
  51917. this._colors32[colidx + 1] = this._particle.color.g;
  51918. this._colors32[colidx + 2] = this._particle.color.b;
  51919. this._colors32[colidx + 3] = this._particle.color.a;
  51920. }
  51921. if (this._computeParticleTexture) {
  51922. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51923. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51924. }
  51925. }
  51926. }
  51927. else {
  51928. this._particle._stillInvisible = true; // mark the particle as invisible
  51929. for (pt = 0; pt < this._shape.length; pt++) {
  51930. idx = index + pt * 3;
  51931. colidx = colorIndex + pt * 4;
  51932. uvidx = uvIndex + pt * 2;
  51933. this._positions32[idx] = 0.0;
  51934. this._positions32[idx + 1] = 0.0;
  51935. this._positions32[idx + 2] = 0.0;
  51936. this._normals32[idx] = 0.0;
  51937. this._normals32[idx + 1] = 0.0;
  51938. this._normals32[idx + 2] = 0.0;
  51939. if (this._computeParticleColor && this._particle.color) {
  51940. this._colors32[colidx] = this._particle.color.r;
  51941. this._colors32[colidx + 1] = this._particle.color.g;
  51942. this._colors32[colidx + 2] = this._particle.color.b;
  51943. this._colors32[colidx + 3] = this._particle.color.a;
  51944. }
  51945. if (this._computeParticleTexture) {
  51946. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51947. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51948. }
  51949. }
  51950. }
  51951. // if the particle intersections must be computed : update the bbInfo
  51952. if (this._particlesIntersect) {
  51953. var bInfo = this._particle._boundingInfo;
  51954. var bBox = bInfo.boundingBox;
  51955. var bSphere = bInfo.boundingSphere;
  51956. if (!this._bSphereOnly) {
  51957. // place, scale and rotate the particle bbox within the SPS local system, then update it
  51958. for (var b = 0; b < bBox.vectors.length; b++) {
  51959. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  51960. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  51961. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  51962. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51963. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51964. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51965. 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;
  51966. 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;
  51967. 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;
  51968. }
  51969. bBox._update(this.mesh._worldMatrix);
  51970. }
  51971. // place and scale the particle bouding sphere in the SPS local system, then update it
  51972. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  51973. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  51974. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  51975. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  51976. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  51977. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  51978. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  51979. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  51980. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  51981. 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));
  51982. bSphere._update(this.mesh._worldMatrix);
  51983. }
  51984. // increment indexes for the next particle
  51985. index = idx + 3;
  51986. colorIndex = colidx + 4;
  51987. uvIndex = uvidx + 2;
  51988. }
  51989. // if the VBO must be updated
  51990. if (update) {
  51991. if (this._computeParticleColor) {
  51992. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  51993. }
  51994. if (this._computeParticleTexture) {
  51995. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  51996. }
  51997. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51998. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  51999. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52000. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52001. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52002. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52003. for (var i = 0; i < this._normals32.length; i++) {
  52004. this._fixedNormal32[i] = this._normals32[i];
  52005. }
  52006. }
  52007. if (!this.mesh.areNormalsFrozen) {
  52008. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52009. }
  52010. }
  52011. if (this._depthSort && this._depthSortParticles) {
  52012. this.depthSortedParticles.sort(this._depthSortFunction);
  52013. var dspl = this.depthSortedParticles.length;
  52014. var sorted = 0;
  52015. var lind = 0;
  52016. var sind = 0;
  52017. var sid = 0;
  52018. for (sorted = 0; sorted < dspl; sorted++) {
  52019. lind = this.depthSortedParticles[sorted].indicesLength;
  52020. sind = this.depthSortedParticles[sorted].ind;
  52021. for (var i = 0; i < lind; i++) {
  52022. this._indices32[sid] = this._indices[sind + i];
  52023. sid++;
  52024. }
  52025. }
  52026. this.mesh.updateIndices(this._indices32);
  52027. }
  52028. }
  52029. if (this._computeBoundingBox) {
  52030. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52031. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52032. }
  52033. this.afterUpdateParticles(start, end, update);
  52034. return this;
  52035. };
  52036. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52037. this._halfroll = this._roll * 0.5;
  52038. this._halfpitch = this._pitch * 0.5;
  52039. this._halfyaw = this._yaw * 0.5;
  52040. this._sinRoll = Math.sin(this._halfroll);
  52041. this._cosRoll = Math.cos(this._halfroll);
  52042. this._sinPitch = Math.sin(this._halfpitch);
  52043. this._cosPitch = Math.cos(this._halfpitch);
  52044. this._sinYaw = Math.sin(this._halfyaw);
  52045. this._cosYaw = Math.cos(this._halfyaw);
  52046. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52047. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52048. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52049. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52050. };
  52051. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52052. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52053. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52054. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52055. this._rotMatrix.m[3] = 0;
  52056. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52057. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52058. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52059. this._rotMatrix.m[7] = 0;
  52060. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52061. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52062. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52063. this._rotMatrix.m[11] = 0;
  52064. this._rotMatrix.m[12] = 0;
  52065. this._rotMatrix.m[13] = 0;
  52066. this._rotMatrix.m[14] = 0;
  52067. this._rotMatrix.m[15] = 1.0;
  52068. };
  52069. /**
  52070. * Disposes the SPS.
  52071. */
  52072. SolidParticleSystem.prototype.dispose = function () {
  52073. this.mesh.dispose();
  52074. this.vars = null;
  52075. // drop references to internal big arrays for the GC
  52076. this._positions = null;
  52077. this._indices = null;
  52078. this._normals = null;
  52079. this._uvs = null;
  52080. this._colors = null;
  52081. this._indices32 = null;
  52082. this._positions32 = null;
  52083. this._normals32 = null;
  52084. this._fixedNormal32 = null;
  52085. this._uvs32 = null;
  52086. this._colors32 = null;
  52087. this.pickedParticles = null;
  52088. };
  52089. /**
  52090. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52091. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52092. * @returns the SPS.
  52093. */
  52094. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52095. if (!this._isVisibilityBoxLocked) {
  52096. this.mesh.refreshBoundingInfo();
  52097. }
  52098. return this;
  52099. };
  52100. /**
  52101. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52102. * @param size the size (float) of the visibility box
  52103. * note : this doesn't lock the SPS mesh bounding box.
  52104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52105. */
  52106. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52107. var vis = size / 2;
  52108. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52109. };
  52110. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52111. /**
  52112. * Gets whether the SPS as always visible or not
  52113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52114. */
  52115. get: function () {
  52116. return this._alwaysVisible;
  52117. },
  52118. /**
  52119. * Sets the SPS as always visible or not
  52120. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52121. */
  52122. set: function (val) {
  52123. this._alwaysVisible = val;
  52124. this.mesh.alwaysSelectAsActiveMesh = val;
  52125. },
  52126. enumerable: true,
  52127. configurable: true
  52128. });
  52129. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52130. /**
  52131. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52132. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52133. */
  52134. get: function () {
  52135. return this._isVisibilityBoxLocked;
  52136. },
  52137. /**
  52138. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52139. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52140. */
  52141. set: function (val) {
  52142. this._isVisibilityBoxLocked = val;
  52143. var boundingInfo = this.mesh.getBoundingInfo();
  52144. boundingInfo.isLocked = val;
  52145. },
  52146. enumerable: true,
  52147. configurable: true
  52148. });
  52149. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52150. /**
  52151. * Gets if `setParticles()` computes the particle rotations or not.
  52152. * Default value : true. The SPS is faster when it's set to false.
  52153. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52154. */
  52155. get: function () {
  52156. return this._computeParticleRotation;
  52157. },
  52158. /**
  52159. * Tells to `setParticles()` to compute the particle rotations or not.
  52160. * Default value : true. The SPS is faster when it's set to false.
  52161. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52162. */
  52163. set: function (val) {
  52164. this._computeParticleRotation = val;
  52165. },
  52166. enumerable: true,
  52167. configurable: true
  52168. });
  52169. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52170. /**
  52171. * Gets if `setParticles()` computes the particle colors or not.
  52172. * Default value : true. The SPS is faster when it's set to false.
  52173. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52174. */
  52175. get: function () {
  52176. return this._computeParticleColor;
  52177. },
  52178. /**
  52179. * Tells to `setParticles()` to compute the particle colors or not.
  52180. * Default value : true. The SPS is faster when it's set to false.
  52181. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52182. */
  52183. set: function (val) {
  52184. this._computeParticleColor = val;
  52185. },
  52186. enumerable: true,
  52187. configurable: true
  52188. });
  52189. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52190. /**
  52191. * Gets if `setParticles()` computes the particle textures or not.
  52192. * Default value : true. The SPS is faster when it's set to false.
  52193. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52194. */
  52195. get: function () {
  52196. return this._computeParticleTexture;
  52197. },
  52198. set: function (val) {
  52199. this._computeParticleTexture = val;
  52200. },
  52201. enumerable: true,
  52202. configurable: true
  52203. });
  52204. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52205. /**
  52206. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52207. * Default value : false. The SPS is faster when it's set to false.
  52208. * Note : the particle custom vertex positions aren't stored values.
  52209. */
  52210. get: function () {
  52211. return this._computeParticleVertex;
  52212. },
  52213. /**
  52214. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52215. * Default value : false. The SPS is faster when it's set to false.
  52216. * Note : the particle custom vertex positions aren't stored values.
  52217. */
  52218. set: function (val) {
  52219. this._computeParticleVertex = val;
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52225. /**
  52226. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52227. */
  52228. get: function () {
  52229. return this._computeBoundingBox;
  52230. },
  52231. /**
  52232. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52233. */
  52234. set: function (val) {
  52235. this._computeBoundingBox = val;
  52236. },
  52237. enumerable: true,
  52238. configurable: true
  52239. });
  52240. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52241. /**
  52242. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52243. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52244. * Default : `true`
  52245. */
  52246. get: function () {
  52247. return this._depthSortParticles;
  52248. },
  52249. /**
  52250. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52251. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52252. * Default : `true`
  52253. */
  52254. set: function (val) {
  52255. this._depthSortParticles = val;
  52256. },
  52257. enumerable: true,
  52258. configurable: true
  52259. });
  52260. // =======================================================================
  52261. // Particle behavior logic
  52262. // these following methods may be overwritten by the user to fit his needs
  52263. /**
  52264. * This function does nothing. It may be overwritten to set all the particle first values.
  52265. * The SPS doesn't call this function, you may have to call it by your own.
  52266. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52267. */
  52268. SolidParticleSystem.prototype.initParticles = function () {
  52269. };
  52270. /**
  52271. * This function does nothing. It may be overwritten to recycle a particle.
  52272. * The SPS doesn't call this function, you may have to call it by your own.
  52273. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52274. * @param particle The particle to recycle
  52275. * @returns the recycled particle
  52276. */
  52277. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52278. return particle;
  52279. };
  52280. /**
  52281. * Updates a particle : this function should be overwritten by the user.
  52282. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52283. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52284. * @example : just set a particle position or velocity and recycle conditions
  52285. * @param particle The particle to update
  52286. * @returns the updated particle
  52287. */
  52288. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52289. return particle;
  52290. };
  52291. /**
  52292. * Updates a vertex of a particle : it can be overwritten by the user.
  52293. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52294. * @param particle the current particle
  52295. * @param vertex the current index of the current particle
  52296. * @param pt the index of the current vertex in the particle shape
  52297. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52298. * @example : just set a vertex particle position
  52299. * @returns the updated vertex
  52300. */
  52301. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52302. return vertex;
  52303. };
  52304. /**
  52305. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52306. * This does nothing and may be overwritten by the user.
  52307. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52308. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52309. * @param update the boolean update value actually passed to setParticles()
  52310. */
  52311. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52312. };
  52313. /**
  52314. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52315. * This will be passed three parameters.
  52316. * This does nothing and may be overwritten by the user.
  52317. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52318. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52319. * @param update the boolean update value actually passed to setParticles()
  52320. */
  52321. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52322. };
  52323. return SolidParticleSystem;
  52324. }());
  52325. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52326. })(BABYLON || (BABYLON = {}));
  52327. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52328. var BABYLON;
  52329. (function (BABYLON) {
  52330. var ShaderMaterial = /** @class */ (function (_super) {
  52331. __extends(ShaderMaterial, _super);
  52332. function ShaderMaterial(name, scene, shaderPath, options) {
  52333. var _this = _super.call(this, name, scene) || this;
  52334. _this._textures = {};
  52335. _this._textureArrays = {};
  52336. _this._floats = {};
  52337. _this._ints = {};
  52338. _this._floatsArrays = {};
  52339. _this._colors3 = {};
  52340. _this._colors3Arrays = {};
  52341. _this._colors4 = {};
  52342. _this._vectors2 = {};
  52343. _this._vectors3 = {};
  52344. _this._vectors4 = {};
  52345. _this._matrices = {};
  52346. _this._matrices3x3 = {};
  52347. _this._matrices2x2 = {};
  52348. _this._vectors2Arrays = {};
  52349. _this._vectors3Arrays = {};
  52350. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52351. _this._shaderPath = shaderPath;
  52352. options.needAlphaBlending = options.needAlphaBlending || false;
  52353. options.needAlphaTesting = options.needAlphaTesting || false;
  52354. options.attributes = options.attributes || ["position", "normal", "uv"];
  52355. options.uniforms = options.uniforms || ["worldViewProjection"];
  52356. options.uniformBuffers = options.uniformBuffers || [];
  52357. options.samplers = options.samplers || [];
  52358. options.defines = options.defines || [];
  52359. _this._options = options;
  52360. return _this;
  52361. }
  52362. ShaderMaterial.prototype.getClassName = function () {
  52363. return "ShaderMaterial";
  52364. };
  52365. ShaderMaterial.prototype.needAlphaBlending = function () {
  52366. return this._options.needAlphaBlending;
  52367. };
  52368. ShaderMaterial.prototype.needAlphaTesting = function () {
  52369. return this._options.needAlphaTesting;
  52370. };
  52371. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52372. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52373. this._options.uniforms.push(uniformName);
  52374. }
  52375. };
  52376. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52377. if (this._options.samplers.indexOf(name) === -1) {
  52378. this._options.samplers.push(name);
  52379. }
  52380. this._textures[name] = texture;
  52381. return this;
  52382. };
  52383. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52384. if (this._options.samplers.indexOf(name) === -1) {
  52385. this._options.samplers.push(name);
  52386. }
  52387. this._checkUniform(name);
  52388. this._textureArrays[name] = textures;
  52389. return this;
  52390. };
  52391. ShaderMaterial.prototype.setFloat = function (name, value) {
  52392. this._checkUniform(name);
  52393. this._floats[name] = value;
  52394. return this;
  52395. };
  52396. ShaderMaterial.prototype.setInt = function (name, value) {
  52397. this._checkUniform(name);
  52398. this._ints[name] = value;
  52399. return this;
  52400. };
  52401. ShaderMaterial.prototype.setFloats = function (name, value) {
  52402. this._checkUniform(name);
  52403. this._floatsArrays[name] = value;
  52404. return this;
  52405. };
  52406. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52407. this._checkUniform(name);
  52408. this._colors3[name] = value;
  52409. return this;
  52410. };
  52411. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52412. this._checkUniform(name);
  52413. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52414. color.toArray(arr, arr.length);
  52415. return arr;
  52416. }, []);
  52417. return this;
  52418. };
  52419. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52420. this._checkUniform(name);
  52421. this._colors4[name] = value;
  52422. return this;
  52423. };
  52424. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52425. this._checkUniform(name);
  52426. this._vectors2[name] = value;
  52427. return this;
  52428. };
  52429. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52430. this._checkUniform(name);
  52431. this._vectors3[name] = value;
  52432. return this;
  52433. };
  52434. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52435. this._checkUniform(name);
  52436. this._vectors4[name] = value;
  52437. return this;
  52438. };
  52439. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52440. this._checkUniform(name);
  52441. this._matrices[name] = value;
  52442. return this;
  52443. };
  52444. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52445. this._checkUniform(name);
  52446. this._matrices3x3[name] = value;
  52447. return this;
  52448. };
  52449. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52450. this._checkUniform(name);
  52451. this._matrices2x2[name] = value;
  52452. return this;
  52453. };
  52454. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52455. this._checkUniform(name);
  52456. this._vectors2Arrays[name] = value;
  52457. return this;
  52458. };
  52459. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52460. this._checkUniform(name);
  52461. this._vectors3Arrays[name] = value;
  52462. return this;
  52463. };
  52464. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52465. if (!mesh) {
  52466. return true;
  52467. }
  52468. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52469. return false;
  52470. }
  52471. return false;
  52472. };
  52473. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52474. var scene = this.getScene();
  52475. var engine = scene.getEngine();
  52476. if (!this.checkReadyOnEveryCall) {
  52477. if (this._renderId === scene.getRenderId()) {
  52478. if (this._checkCache(scene, mesh, useInstances)) {
  52479. return true;
  52480. }
  52481. }
  52482. }
  52483. // Instances
  52484. var defines = [];
  52485. var attribs = [];
  52486. var fallbacks = new BABYLON.EffectFallbacks();
  52487. if (useInstances) {
  52488. defines.push("#define INSTANCES");
  52489. }
  52490. for (var index = 0; index < this._options.defines.length; index++) {
  52491. defines.push(this._options.defines[index]);
  52492. }
  52493. for (var index = 0; index < this._options.attributes.length; index++) {
  52494. attribs.push(this._options.attributes[index]);
  52495. }
  52496. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52497. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52498. defines.push("#define VERTEXCOLOR");
  52499. }
  52500. // Bones
  52501. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52502. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52503. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52504. if (mesh.numBoneInfluencers > 4) {
  52505. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52506. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52507. }
  52508. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52509. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52510. fallbacks.addCPUSkinningFallback(0, mesh);
  52511. if (this._options.uniforms.indexOf("mBones") === -1) {
  52512. this._options.uniforms.push("mBones");
  52513. }
  52514. }
  52515. else {
  52516. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52517. }
  52518. // Textures
  52519. for (var name in this._textures) {
  52520. if (!this._textures[name].isReady()) {
  52521. return false;
  52522. }
  52523. }
  52524. // Alpha test
  52525. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52526. defines.push("#define ALPHATEST");
  52527. }
  52528. var previousEffect = this._effect;
  52529. var join = defines.join("\n");
  52530. this._effect = engine.createEffect(this._shaderPath, {
  52531. attributes: attribs,
  52532. uniformsNames: this._options.uniforms,
  52533. uniformBuffersNames: this._options.uniformBuffers,
  52534. samplers: this._options.samplers,
  52535. defines: join,
  52536. fallbacks: fallbacks,
  52537. onCompiled: this.onCompiled,
  52538. onError: this.onError
  52539. }, engine);
  52540. if (!this._effect.isReady()) {
  52541. return false;
  52542. }
  52543. if (previousEffect !== this._effect) {
  52544. scene.resetCachedMaterial();
  52545. }
  52546. this._renderId = scene.getRenderId();
  52547. return true;
  52548. };
  52549. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52550. var scene = this.getScene();
  52551. if (!this._effect) {
  52552. return;
  52553. }
  52554. if (this._options.uniforms.indexOf("world") !== -1) {
  52555. this._effect.setMatrix("world", world);
  52556. }
  52557. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52558. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52559. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52560. }
  52561. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52562. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52563. }
  52564. };
  52565. ShaderMaterial.prototype.bind = function (world, mesh) {
  52566. // Std values
  52567. this.bindOnlyWorldMatrix(world);
  52568. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52569. if (this._options.uniforms.indexOf("view") !== -1) {
  52570. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52571. }
  52572. if (this._options.uniforms.indexOf("projection") !== -1) {
  52573. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52574. }
  52575. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52576. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52577. }
  52578. // Bones
  52579. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52580. var name;
  52581. // Texture
  52582. for (name in this._textures) {
  52583. this._effect.setTexture(name, this._textures[name]);
  52584. }
  52585. // Texture arrays
  52586. for (name in this._textureArrays) {
  52587. this._effect.setTextureArray(name, this._textureArrays[name]);
  52588. }
  52589. // Int
  52590. for (name in this._ints) {
  52591. this._effect.setInt(name, this._ints[name]);
  52592. }
  52593. // Float
  52594. for (name in this._floats) {
  52595. this._effect.setFloat(name, this._floats[name]);
  52596. }
  52597. // Floats
  52598. for (name in this._floatsArrays) {
  52599. this._effect.setArray(name, this._floatsArrays[name]);
  52600. }
  52601. // Color3
  52602. for (name in this._colors3) {
  52603. this._effect.setColor3(name, this._colors3[name]);
  52604. }
  52605. for (name in this._colors3Arrays) {
  52606. this._effect.setArray3(name, this._colors3Arrays[name]);
  52607. }
  52608. // Color4
  52609. for (name in this._colors4) {
  52610. var color = this._colors4[name];
  52611. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52612. }
  52613. // Vector2
  52614. for (name in this._vectors2) {
  52615. this._effect.setVector2(name, this._vectors2[name]);
  52616. }
  52617. // Vector3
  52618. for (name in this._vectors3) {
  52619. this._effect.setVector3(name, this._vectors3[name]);
  52620. }
  52621. // Vector4
  52622. for (name in this._vectors4) {
  52623. this._effect.setVector4(name, this._vectors4[name]);
  52624. }
  52625. // Matrix
  52626. for (name in this._matrices) {
  52627. this._effect.setMatrix(name, this._matrices[name]);
  52628. }
  52629. // Matrix 3x3
  52630. for (name in this._matrices3x3) {
  52631. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52632. }
  52633. // Matrix 2x2
  52634. for (name in this._matrices2x2) {
  52635. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52636. }
  52637. // Vector2Array
  52638. for (name in this._vectors2Arrays) {
  52639. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52640. }
  52641. // Vector3Array
  52642. for (name in this._vectors3Arrays) {
  52643. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52644. }
  52645. }
  52646. this._afterBind(mesh);
  52647. };
  52648. ShaderMaterial.prototype.getActiveTextures = function () {
  52649. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52650. for (var name in this._textures) {
  52651. activeTextures.push(this._textures[name]);
  52652. }
  52653. for (var name in this._textureArrays) {
  52654. var array = this._textureArrays[name];
  52655. for (var index = 0; index < array.length; index++) {
  52656. activeTextures.push(array[index]);
  52657. }
  52658. }
  52659. return activeTextures;
  52660. };
  52661. ShaderMaterial.prototype.hasTexture = function (texture) {
  52662. if (_super.prototype.hasTexture.call(this, texture)) {
  52663. return true;
  52664. }
  52665. for (var name in this._textures) {
  52666. if (this._textures[name] === texture) {
  52667. return true;
  52668. }
  52669. }
  52670. for (var name in this._textureArrays) {
  52671. var array = this._textureArrays[name];
  52672. for (var index = 0; index < array.length; index++) {
  52673. if (array[index] === texture) {
  52674. return true;
  52675. }
  52676. }
  52677. }
  52678. return false;
  52679. };
  52680. ShaderMaterial.prototype.clone = function (name) {
  52681. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52682. return newShaderMaterial;
  52683. };
  52684. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52685. if (forceDisposeTextures) {
  52686. var name;
  52687. for (name in this._textures) {
  52688. this._textures[name].dispose();
  52689. }
  52690. for (name in this._textureArrays) {
  52691. var array = this._textureArrays[name];
  52692. for (var index = 0; index < array.length; index++) {
  52693. array[index].dispose();
  52694. }
  52695. }
  52696. }
  52697. this._textures = {};
  52698. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52699. };
  52700. ShaderMaterial.prototype.serialize = function () {
  52701. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52702. serializationObject.customType = "BABYLON.ShaderMaterial";
  52703. serializationObject.options = this._options;
  52704. serializationObject.shaderPath = this._shaderPath;
  52705. var name;
  52706. // Texture
  52707. serializationObject.textures = {};
  52708. for (name in this._textures) {
  52709. serializationObject.textures[name] = this._textures[name].serialize();
  52710. }
  52711. // Texture arrays
  52712. serializationObject.textureArrays = {};
  52713. for (name in this._textureArrays) {
  52714. serializationObject.textureArrays[name] = [];
  52715. var array = this._textureArrays[name];
  52716. for (var index = 0; index < array.length; index++) {
  52717. serializationObject.textureArrays[name].push(array[index].serialize());
  52718. }
  52719. }
  52720. // Float
  52721. serializationObject.floats = {};
  52722. for (name in this._floats) {
  52723. serializationObject.floats[name] = this._floats[name];
  52724. }
  52725. // Float s
  52726. serializationObject.FloatArrays = {};
  52727. for (name in this._floatsArrays) {
  52728. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52729. }
  52730. // Color3
  52731. serializationObject.colors3 = {};
  52732. for (name in this._colors3) {
  52733. serializationObject.colors3[name] = this._colors3[name].asArray();
  52734. }
  52735. // Color3 array
  52736. serializationObject.colors3Arrays = {};
  52737. for (name in this._colors3Arrays) {
  52738. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52739. }
  52740. // Color4
  52741. serializationObject.colors4 = {};
  52742. for (name in this._colors4) {
  52743. serializationObject.colors4[name] = this._colors4[name].asArray();
  52744. }
  52745. // Vector2
  52746. serializationObject.vectors2 = {};
  52747. for (name in this._vectors2) {
  52748. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52749. }
  52750. // Vector3
  52751. serializationObject.vectors3 = {};
  52752. for (name in this._vectors3) {
  52753. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52754. }
  52755. // Vector4
  52756. serializationObject.vectors4 = {};
  52757. for (name in this._vectors4) {
  52758. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52759. }
  52760. // Matrix
  52761. serializationObject.matrices = {};
  52762. for (name in this._matrices) {
  52763. serializationObject.matrices[name] = this._matrices[name].asArray();
  52764. }
  52765. // Matrix 3x3
  52766. serializationObject.matrices3x3 = {};
  52767. for (name in this._matrices3x3) {
  52768. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52769. }
  52770. // Matrix 2x2
  52771. serializationObject.matrices2x2 = {};
  52772. for (name in this._matrices2x2) {
  52773. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52774. }
  52775. // Vector2Array
  52776. serializationObject.vectors2Arrays = {};
  52777. for (name in this._vectors2Arrays) {
  52778. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52779. }
  52780. // Vector3Array
  52781. serializationObject.vectors3Arrays = {};
  52782. for (name in this._vectors3Arrays) {
  52783. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52784. }
  52785. return serializationObject;
  52786. };
  52787. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52788. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52789. var name;
  52790. // Texture
  52791. for (name in source.textures) {
  52792. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52793. }
  52794. // Texture arrays
  52795. for (name in source.textureArrays) {
  52796. var array = source.textureArrays[name];
  52797. var textureArray = new Array();
  52798. for (var index = 0; index < array.length; index++) {
  52799. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52800. }
  52801. material.setTextureArray(name, textureArray);
  52802. }
  52803. // Float
  52804. for (name in source.floats) {
  52805. material.setFloat(name, source.floats[name]);
  52806. }
  52807. // Float s
  52808. for (name in source.floatsArrays) {
  52809. material.setFloats(name, source.floatsArrays[name]);
  52810. }
  52811. // Color3
  52812. for (name in source.colors3) {
  52813. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52814. }
  52815. // Color3 arrays
  52816. for (name in source.colors3Arrays) {
  52817. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52818. if (i % 3 === 0) {
  52819. arr.push([num]);
  52820. }
  52821. else {
  52822. arr[arr.length - 1].push(num);
  52823. }
  52824. return arr;
  52825. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52826. material.setColor3Array(name, colors);
  52827. }
  52828. // Color4
  52829. for (name in source.colors4) {
  52830. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52831. }
  52832. // Vector2
  52833. for (name in source.vectors2) {
  52834. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52835. }
  52836. // Vector3
  52837. for (name in source.vectors3) {
  52838. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52839. }
  52840. // Vector4
  52841. for (name in source.vectors4) {
  52842. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52843. }
  52844. // Matrix
  52845. for (name in source.matrices) {
  52846. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52847. }
  52848. // Matrix 3x3
  52849. for (name in source.matrices3x3) {
  52850. material.setMatrix3x3(name, source.matrices3x3[name]);
  52851. }
  52852. // Matrix 2x2
  52853. for (name in source.matrices2x2) {
  52854. material.setMatrix2x2(name, source.matrices2x2[name]);
  52855. }
  52856. // Vector2Array
  52857. for (name in source.vectors2Arrays) {
  52858. material.setArray2(name, source.vectors2Arrays[name]);
  52859. }
  52860. // Vector3Array
  52861. for (name in source.vectors3Arrays) {
  52862. material.setArray3(name, source.vectors3Arrays[name]);
  52863. }
  52864. return material;
  52865. };
  52866. return ShaderMaterial;
  52867. }(BABYLON.Material));
  52868. BABYLON.ShaderMaterial = ShaderMaterial;
  52869. })(BABYLON || (BABYLON = {}));
  52870. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52871. var BABYLON;
  52872. (function (BABYLON) {
  52873. var GroundMesh = /** @class */ (function (_super) {
  52874. __extends(GroundMesh, _super);
  52875. function GroundMesh(name, scene) {
  52876. var _this = _super.call(this, name, scene) || this;
  52877. _this.generateOctree = false;
  52878. return _this;
  52879. }
  52880. GroundMesh.prototype.getClassName = function () {
  52881. return "GroundMesh";
  52882. };
  52883. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  52884. get: function () {
  52885. return Math.min(this._subdivisionsX, this._subdivisionsY);
  52886. },
  52887. enumerable: true,
  52888. configurable: true
  52889. });
  52890. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  52891. get: function () {
  52892. return this._subdivisionsX;
  52893. },
  52894. enumerable: true,
  52895. configurable: true
  52896. });
  52897. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  52898. get: function () {
  52899. return this._subdivisionsY;
  52900. },
  52901. enumerable: true,
  52902. configurable: true
  52903. });
  52904. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  52905. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  52906. this._subdivisionsX = chunksCount;
  52907. this._subdivisionsY = chunksCount;
  52908. this.subdivide(chunksCount);
  52909. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  52910. };
  52911. /**
  52912. * Returns a height (y) value in the Worl system :
  52913. * the ground altitude at the coordinates (x, z) expressed in the World system.
  52914. * Returns the ground y position if (x, z) are outside the ground surface.
  52915. */
  52916. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  52917. var world = this.getWorldMatrix();
  52918. var invMat = BABYLON.Tmp.Matrix[5];
  52919. world.invertToRef(invMat);
  52920. var tmpVect = BABYLON.Tmp.Vector3[8];
  52921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  52922. x = tmpVect.x;
  52923. z = tmpVect.z;
  52924. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52925. return this.position.y;
  52926. }
  52927. if (!this._heightQuads || this._heightQuads.length == 0) {
  52928. this._initHeightQuads();
  52929. this._computeHeightQuads();
  52930. }
  52931. var facet = this._getFacetAt(x, z);
  52932. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  52933. // return y in the World system
  52934. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  52935. return tmpVect.y;
  52936. };
  52937. /**
  52938. * Returns a normalized vector (Vector3) orthogonal to the ground
  52939. * at the ground coordinates (x, z) expressed in the World system.
  52940. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  52941. */
  52942. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  52943. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  52944. this.getNormalAtCoordinatesToRef(x, z, normal);
  52945. return normal;
  52946. };
  52947. /**
  52948. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  52949. * at the ground coordinates (x, z) expressed in the World system.
  52950. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  52951. * Returns the GroundMesh.
  52952. */
  52953. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  52954. var world = this.getWorldMatrix();
  52955. var tmpMat = BABYLON.Tmp.Matrix[5];
  52956. world.invertToRef(tmpMat);
  52957. var tmpVect = BABYLON.Tmp.Vector3[8];
  52958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  52959. x = tmpVect.x;
  52960. z = tmpVect.z;
  52961. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52962. return this;
  52963. }
  52964. if (!this._heightQuads || this._heightQuads.length == 0) {
  52965. this._initHeightQuads();
  52966. this._computeHeightQuads();
  52967. }
  52968. var facet = this._getFacetAt(x, z);
  52969. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  52970. return this;
  52971. };
  52972. /**
  52973. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  52974. * if the ground has been updated.
  52975. * This can be used in the render loop.
  52976. * Returns the GroundMesh.
  52977. */
  52978. GroundMesh.prototype.updateCoordinateHeights = function () {
  52979. if (!this._heightQuads || this._heightQuads.length == 0) {
  52980. this._initHeightQuads();
  52981. }
  52982. this._computeHeightQuads();
  52983. return this;
  52984. };
  52985. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  52986. GroundMesh.prototype._getFacetAt = function (x, z) {
  52987. // retrieve col and row from x, z coordinates in the ground local system
  52988. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  52989. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  52990. var quad = this._heightQuads[row * this._subdivisionsX + col];
  52991. var facet;
  52992. if (z < quad.slope.x * x + quad.slope.y) {
  52993. facet = quad.facet1;
  52994. }
  52995. else {
  52996. facet = quad.facet2;
  52997. }
  52998. return facet;
  52999. };
  53000. // Creates and populates the heightMap array with "facet" elements :
  53001. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53002. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53003. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53004. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53005. // Returns the GroundMesh.
  53006. GroundMesh.prototype._initHeightQuads = function () {
  53007. var subdivisionsX = this._subdivisionsX;
  53008. var subdivisionsY = this._subdivisionsY;
  53009. this._heightQuads = new Array();
  53010. for (var row = 0; row < subdivisionsY; row++) {
  53011. for (var col = 0; col < subdivisionsX; col++) {
  53012. 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) };
  53013. this._heightQuads[row * subdivisionsX + col] = quad;
  53014. }
  53015. }
  53016. return this;
  53017. };
  53018. // Compute each quad element values and update the the heightMap array :
  53019. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53020. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53021. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53022. // Returns the GroundMesh.
  53023. GroundMesh.prototype._computeHeightQuads = function () {
  53024. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53025. if (!positions) {
  53026. return this;
  53027. }
  53028. var v1 = BABYLON.Tmp.Vector3[3];
  53029. var v2 = BABYLON.Tmp.Vector3[2];
  53030. var v3 = BABYLON.Tmp.Vector3[1];
  53031. var v4 = BABYLON.Tmp.Vector3[0];
  53032. var v1v2 = BABYLON.Tmp.Vector3[4];
  53033. var v1v3 = BABYLON.Tmp.Vector3[5];
  53034. var v1v4 = BABYLON.Tmp.Vector3[6];
  53035. var norm1 = BABYLON.Tmp.Vector3[7];
  53036. var norm2 = BABYLON.Tmp.Vector3[8];
  53037. var i = 0;
  53038. var j = 0;
  53039. var k = 0;
  53040. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53041. var h = 0;
  53042. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53043. var d2 = 0;
  53044. var subdivisionsX = this._subdivisionsX;
  53045. var subdivisionsY = this._subdivisionsY;
  53046. for (var row = 0; row < subdivisionsY; row++) {
  53047. for (var col = 0; col < subdivisionsX; col++) {
  53048. i = col * 3;
  53049. j = row * (subdivisionsX + 1) * 3;
  53050. k = (row + 1) * (subdivisionsX + 1) * 3;
  53051. v1.x = positions[j + i];
  53052. v1.y = positions[j + i + 1];
  53053. v1.z = positions[j + i + 2];
  53054. v2.x = positions[j + i + 3];
  53055. v2.y = positions[j + i + 4];
  53056. v2.z = positions[j + i + 5];
  53057. v3.x = positions[k + i];
  53058. v3.y = positions[k + i + 1];
  53059. v3.z = positions[k + i + 2];
  53060. v4.x = positions[k + i + 3];
  53061. v4.y = positions[k + i + 4];
  53062. v4.z = positions[k + i + 5];
  53063. // 2D slope V1V4
  53064. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53065. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53066. // facet equations :
  53067. // we compute each facet normal vector
  53068. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53069. // we compute the value d by applying the equation to v1 which belongs to the plane
  53070. // then we store the facet equation in a Vector4
  53071. v2.subtractToRef(v1, v1v2);
  53072. v3.subtractToRef(v1, v1v3);
  53073. v4.subtractToRef(v1, v1v4);
  53074. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53075. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53076. norm1.normalize();
  53077. norm2.normalize();
  53078. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53079. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53080. var quad = this._heightQuads[row * subdivisionsX + col];
  53081. quad.slope.copyFromFloats(cd, h);
  53082. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53083. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53084. }
  53085. }
  53086. return this;
  53087. };
  53088. GroundMesh.prototype.serialize = function (serializationObject) {
  53089. _super.prototype.serialize.call(this, serializationObject);
  53090. serializationObject.subdivisionsX = this._subdivisionsX;
  53091. serializationObject.subdivisionsY = this._subdivisionsY;
  53092. serializationObject.minX = this._minX;
  53093. serializationObject.maxX = this._maxX;
  53094. serializationObject.minZ = this._minZ;
  53095. serializationObject.maxZ = this._maxZ;
  53096. serializationObject.width = this._width;
  53097. serializationObject.height = this._height;
  53098. };
  53099. GroundMesh.Parse = function (parsedMesh, scene) {
  53100. var result = new GroundMesh(parsedMesh.name, scene);
  53101. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53102. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53103. result._minX = parsedMesh.minX;
  53104. result._maxX = parsedMesh.maxX;
  53105. result._minZ = parsedMesh.minZ;
  53106. result._maxZ = parsedMesh.maxZ;
  53107. result._width = parsedMesh.width;
  53108. result._height = parsedMesh.height;
  53109. return result;
  53110. };
  53111. return GroundMesh;
  53112. }(BABYLON.Mesh));
  53113. BABYLON.GroundMesh = GroundMesh;
  53114. })(BABYLON || (BABYLON = {}));
  53115. //# sourceMappingURL=babylon.groundMesh.js.map
  53116. var BABYLON;
  53117. (function (BABYLON) {
  53118. /**
  53119. * Creates an instance based on a source mesh.
  53120. */
  53121. var InstancedMesh = /** @class */ (function (_super) {
  53122. __extends(InstancedMesh, _super);
  53123. function InstancedMesh(name, source) {
  53124. var _this = _super.call(this, name, source.getScene()) || this;
  53125. source.instances.push(_this);
  53126. _this._sourceMesh = source;
  53127. _this.position.copyFrom(source.position);
  53128. _this.rotation.copyFrom(source.rotation);
  53129. _this.scaling.copyFrom(source.scaling);
  53130. if (source.rotationQuaternion) {
  53131. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53132. }
  53133. _this.infiniteDistance = source.infiniteDistance;
  53134. _this.setPivotMatrix(source.getPivotMatrix());
  53135. _this.refreshBoundingInfo();
  53136. _this._syncSubMeshes();
  53137. return _this;
  53138. }
  53139. /**
  53140. * Returns the string "InstancedMesh".
  53141. */
  53142. InstancedMesh.prototype.getClassName = function () {
  53143. return "InstancedMesh";
  53144. };
  53145. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53146. // Methods
  53147. get: function () {
  53148. return this._sourceMesh.receiveShadows;
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. Object.defineProperty(InstancedMesh.prototype, "material", {
  53154. get: function () {
  53155. return this._sourceMesh.material;
  53156. },
  53157. enumerable: true,
  53158. configurable: true
  53159. });
  53160. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53161. get: function () {
  53162. return this._sourceMesh.visibility;
  53163. },
  53164. enumerable: true,
  53165. configurable: true
  53166. });
  53167. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53168. get: function () {
  53169. return this._sourceMesh.skeleton;
  53170. },
  53171. enumerable: true,
  53172. configurable: true
  53173. });
  53174. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53175. get: function () {
  53176. return this._sourceMesh.renderingGroupId;
  53177. },
  53178. enumerable: true,
  53179. configurable: true
  53180. });
  53181. /**
  53182. * Returns the total number of vertices (integer).
  53183. */
  53184. InstancedMesh.prototype.getTotalVertices = function () {
  53185. return this._sourceMesh.getTotalVertices();
  53186. };
  53187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53188. get: function () {
  53189. return this._sourceMesh;
  53190. },
  53191. enumerable: true,
  53192. configurable: true
  53193. });
  53194. /**
  53195. * Is this node ready to be used/rendered
  53196. * @return {boolean} is it ready
  53197. */
  53198. InstancedMesh.prototype.isReady = function () {
  53199. return this._sourceMesh.isReady(true);
  53200. };
  53201. /**
  53202. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53203. */
  53204. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53205. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53206. };
  53207. /**
  53208. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53209. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53210. * The `data` are either a numeric array either a Float32Array.
  53211. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53212. * 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).
  53213. * Note that a new underlying VertexBuffer object is created each call.
  53214. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53215. *
  53216. * Possible `kind` values :
  53217. * - BABYLON.VertexBuffer.PositionKind
  53218. * - BABYLON.VertexBuffer.UVKind
  53219. * - BABYLON.VertexBuffer.UV2Kind
  53220. * - BABYLON.VertexBuffer.UV3Kind
  53221. * - BABYLON.VertexBuffer.UV4Kind
  53222. * - BABYLON.VertexBuffer.UV5Kind
  53223. * - BABYLON.VertexBuffer.UV6Kind
  53224. * - BABYLON.VertexBuffer.ColorKind
  53225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53229. *
  53230. * Returns the Mesh.
  53231. */
  53232. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53233. if (this.sourceMesh) {
  53234. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53235. }
  53236. return this.sourceMesh;
  53237. };
  53238. /**
  53239. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53240. * If the mesh has no geometry, it is simply returned as it is.
  53241. * The `data` are either a numeric array either a Float32Array.
  53242. * No new underlying VertexBuffer object is created.
  53243. * 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.
  53244. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53245. *
  53246. * Possible `kind` values :
  53247. * - BABYLON.VertexBuffer.PositionKind
  53248. * - BABYLON.VertexBuffer.UVKind
  53249. * - BABYLON.VertexBuffer.UV2Kind
  53250. * - BABYLON.VertexBuffer.UV3Kind
  53251. * - BABYLON.VertexBuffer.UV4Kind
  53252. * - BABYLON.VertexBuffer.UV5Kind
  53253. * - BABYLON.VertexBuffer.UV6Kind
  53254. * - BABYLON.VertexBuffer.ColorKind
  53255. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53256. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53257. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53258. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53259. *
  53260. * Returns the Mesh.
  53261. */
  53262. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53263. if (this.sourceMesh) {
  53264. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53265. }
  53266. return this.sourceMesh;
  53267. };
  53268. /**
  53269. * Sets the mesh indices.
  53270. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53271. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53272. * This method creates a new index buffer each call.
  53273. * Returns the Mesh.
  53274. */
  53275. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53276. if (totalVertices === void 0) { totalVertices = null; }
  53277. if (this.sourceMesh) {
  53278. this.sourceMesh.setIndices(indices, totalVertices);
  53279. }
  53280. return this.sourceMesh;
  53281. };
  53282. /**
  53283. * Boolean : True if the mesh owns the requested kind of data.
  53284. */
  53285. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53286. return this._sourceMesh.isVerticesDataPresent(kind);
  53287. };
  53288. /**
  53289. * Returns an array of indices (IndicesArray).
  53290. */
  53291. InstancedMesh.prototype.getIndices = function () {
  53292. return this._sourceMesh.getIndices();
  53293. };
  53294. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53295. get: function () {
  53296. return this._sourceMesh._positions;
  53297. },
  53298. enumerable: true,
  53299. configurable: true
  53300. });
  53301. /**
  53302. * Sets a new updated BoundingInfo to the mesh.
  53303. * Returns the mesh.
  53304. */
  53305. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53306. var meshBB = this._sourceMesh.getBoundingInfo();
  53307. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53308. this._updateBoundingInfo();
  53309. return this;
  53310. };
  53311. InstancedMesh.prototype._preActivate = function () {
  53312. if (this._currentLOD) {
  53313. this._currentLOD._preActivate();
  53314. }
  53315. return this;
  53316. };
  53317. InstancedMesh.prototype._activate = function (renderId) {
  53318. if (this._currentLOD) {
  53319. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53320. }
  53321. return this;
  53322. };
  53323. /**
  53324. * Returns the current associated LOD AbstractMesh.
  53325. */
  53326. InstancedMesh.prototype.getLOD = function (camera) {
  53327. if (!camera) {
  53328. return this;
  53329. }
  53330. var boundingInfo = this.getBoundingInfo();
  53331. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53332. if (this._currentLOD === this.sourceMesh) {
  53333. return this;
  53334. }
  53335. return this._currentLOD;
  53336. };
  53337. InstancedMesh.prototype._syncSubMeshes = function () {
  53338. this.releaseSubMeshes();
  53339. if (this._sourceMesh.subMeshes) {
  53340. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53341. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53342. }
  53343. }
  53344. return this;
  53345. };
  53346. InstancedMesh.prototype._generatePointsArray = function () {
  53347. return this._sourceMesh._generatePointsArray();
  53348. };
  53349. /**
  53350. * Creates a new InstancedMesh from the current mesh.
  53351. * - name (string) : the cloned mesh name
  53352. * - newParent (optional Node) : the optional Node to parent the clone to.
  53353. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53354. *
  53355. * Returns the clone.
  53356. */
  53357. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53358. var result = this._sourceMesh.createInstance(name);
  53359. // Deep copy
  53360. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53361. // Bounding info
  53362. this.refreshBoundingInfo();
  53363. // Parent
  53364. if (newParent) {
  53365. result.parent = newParent;
  53366. }
  53367. if (!doNotCloneChildren) {
  53368. // Children
  53369. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53370. var mesh = this.getScene().meshes[index];
  53371. if (mesh.parent === this) {
  53372. mesh.clone(mesh.name, result);
  53373. }
  53374. }
  53375. }
  53376. result.computeWorldMatrix(true);
  53377. return result;
  53378. };
  53379. /**
  53380. * Disposes the InstancedMesh.
  53381. * Returns nothing.
  53382. */
  53383. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53384. // Remove from mesh
  53385. var index = this._sourceMesh.instances.indexOf(this);
  53386. this._sourceMesh.instances.splice(index, 1);
  53387. _super.prototype.dispose.call(this, doNotRecurse);
  53388. };
  53389. return InstancedMesh;
  53390. }(BABYLON.AbstractMesh));
  53391. BABYLON.InstancedMesh = InstancedMesh;
  53392. })(BABYLON || (BABYLON = {}));
  53393. //# sourceMappingURL=babylon.instancedMesh.js.map
  53394. var BABYLON;
  53395. (function (BABYLON) {
  53396. var LinesMesh = /** @class */ (function (_super) {
  53397. __extends(LinesMesh, _super);
  53398. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53399. if (scene === void 0) { scene = null; }
  53400. if (parent === void 0) { parent = null; }
  53401. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53402. _this.useVertexColor = useVertexColor;
  53403. _this.useVertexAlpha = useVertexAlpha;
  53404. _this.color = new BABYLON.Color3(1, 1, 1);
  53405. _this.alpha = 1;
  53406. if (source) {
  53407. _this.color = source.color.clone();
  53408. _this.alpha = source.alpha;
  53409. _this.useVertexColor = source.useVertexColor;
  53410. _this.useVertexAlpha = source.useVertexAlpha;
  53411. }
  53412. _this._intersectionThreshold = 0.1;
  53413. var defines = [];
  53414. var options = {
  53415. attributes: [BABYLON.VertexBuffer.PositionKind],
  53416. uniforms: ["world", "viewProjection"],
  53417. needAlphaBlending: true,
  53418. defines: defines
  53419. };
  53420. if (useVertexAlpha === false) {
  53421. options.needAlphaBlending = false;
  53422. }
  53423. if (!useVertexColor) {
  53424. options.uniforms.push("color");
  53425. }
  53426. else {
  53427. options.defines.push("#define VERTEXCOLOR");
  53428. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53429. }
  53430. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53431. return _this;
  53432. }
  53433. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53434. /**
  53435. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53436. * This margin is expressed in world space coordinates, so its value may vary.
  53437. * Default value is 0.1
  53438. * @returns the intersection Threshold value.
  53439. */
  53440. get: function () {
  53441. return this._intersectionThreshold;
  53442. },
  53443. /**
  53444. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53445. * This margin is expressed in world space coordinates, so its value may vary.
  53446. * @param value the new threshold to apply
  53447. */
  53448. set: function (value) {
  53449. if (this._intersectionThreshold === value) {
  53450. return;
  53451. }
  53452. this._intersectionThreshold = value;
  53453. if (this.geometry) {
  53454. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53455. }
  53456. },
  53457. enumerable: true,
  53458. configurable: true
  53459. });
  53460. /**
  53461. * Returns the string "LineMesh"
  53462. */
  53463. LinesMesh.prototype.getClassName = function () {
  53464. return "LinesMesh";
  53465. };
  53466. Object.defineProperty(LinesMesh.prototype, "material", {
  53467. get: function () {
  53468. return this._colorShader;
  53469. },
  53470. set: function (value) {
  53471. // Do nothing
  53472. },
  53473. enumerable: true,
  53474. configurable: true
  53475. });
  53476. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53477. get: function () {
  53478. return false;
  53479. },
  53480. enumerable: true,
  53481. configurable: true
  53482. });
  53483. LinesMesh.prototype.createInstance = function (name) {
  53484. throw new Error("LinesMeshes do not support createInstance.");
  53485. };
  53486. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53487. if (!this._geometry) {
  53488. return this;
  53489. }
  53490. // VBOs
  53491. this._geometry._bind(this._colorShader.getEffect());
  53492. // Color
  53493. if (!this.useVertexColor) {
  53494. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53495. }
  53496. return this;
  53497. };
  53498. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53500. return this;
  53501. }
  53502. var engine = this.getScene().getEngine();
  53503. // Draw order
  53504. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53505. return this;
  53506. };
  53507. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53508. this._colorShader.dispose();
  53509. _super.prototype.dispose.call(this, doNotRecurse);
  53510. };
  53511. /**
  53512. * Returns a new LineMesh object cloned from the current one.
  53513. */
  53514. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53515. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53516. };
  53517. return LinesMesh;
  53518. }(BABYLON.Mesh));
  53519. BABYLON.LinesMesh = LinesMesh;
  53520. })(BABYLON || (BABYLON = {}));
  53521. //# sourceMappingURL=babylon.linesMesh.js.map
  53522. var BABYLON;
  53523. (function (BABYLON) {
  53524. var MeshBuilder = /** @class */ (function () {
  53525. function MeshBuilder() {
  53526. }
  53527. MeshBuilder.updateSideOrientation = function (orientation) {
  53528. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53529. return BABYLON.Mesh.DOUBLESIDE;
  53530. }
  53531. if (orientation === undefined || orientation === null) {
  53532. return BABYLON.Mesh.FRONTSIDE;
  53533. }
  53534. return orientation;
  53535. };
  53536. /**
  53537. * Creates a box mesh.
  53538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53539. * The parameter `size` sets the size (float) of each box side (default 1).
  53540. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53541. * 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).
  53542. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53544. * 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).
  53545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53547. */
  53548. MeshBuilder.CreateBox = function (name, options, scene) {
  53549. if (scene === void 0) { scene = null; }
  53550. var box = new BABYLON.Mesh(name, scene);
  53551. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53552. box._originalBuilderSideOrientation = options.sideOrientation;
  53553. var vertexData = BABYLON.VertexData.CreateBox(options);
  53554. vertexData.applyToMesh(box, options.updatable);
  53555. return box;
  53556. };
  53557. /**
  53558. * Creates a sphere mesh.
  53559. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53560. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53561. * 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`).
  53562. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53563. * 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
  53564. * 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).
  53565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53566. * 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).
  53567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53569. */
  53570. MeshBuilder.CreateSphere = function (name, options, scene) {
  53571. var sphere = new BABYLON.Mesh(name, scene);
  53572. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53573. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53574. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53575. vertexData.applyToMesh(sphere, options.updatable);
  53576. return sphere;
  53577. };
  53578. /**
  53579. * Creates a plane polygonal mesh. By default, this is a disc.
  53580. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53581. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53582. * 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.
  53583. * 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
  53584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53585. * 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).
  53586. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53588. */
  53589. MeshBuilder.CreateDisc = function (name, options, scene) {
  53590. if (scene === void 0) { scene = null; }
  53591. var disc = new BABYLON.Mesh(name, scene);
  53592. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53593. disc._originalBuilderSideOrientation = options.sideOrientation;
  53594. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53595. vertexData.applyToMesh(disc, options.updatable);
  53596. return disc;
  53597. };
  53598. /**
  53599. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53600. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53601. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53602. * 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`).
  53603. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53604. * 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.
  53605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53606. * 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).
  53607. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53609. */
  53610. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53611. var sphere = new BABYLON.Mesh(name, scene);
  53612. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53613. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53614. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53615. vertexData.applyToMesh(sphere, options.updatable);
  53616. return sphere;
  53617. };
  53618. ;
  53619. /**
  53620. * Creates a ribbon mesh.
  53621. * 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.
  53622. *
  53623. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53624. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53625. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53626. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53627. * 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.
  53628. * 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.
  53629. * 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
  53630. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53631. * 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).
  53632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53633. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53634. * 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.
  53635. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53636. * 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
  53637. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53638. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53640. */
  53641. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53642. if (scene === void 0) { scene = null; }
  53643. var pathArray = options.pathArray;
  53644. var closeArray = options.closeArray;
  53645. var closePath = options.closePath;
  53646. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53647. var instance = options.instance;
  53648. var updatable = options.updatable;
  53649. if (instance) {
  53650. // positionFunction : ribbon case
  53651. // only pathArray and sideOrientation parameters are taken into account for positions update
  53652. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53653. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53654. var positionFunction = function (positions) {
  53655. var minlg = pathArray[0].length;
  53656. var i = 0;
  53657. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53658. for (var si = 1; si <= ns; si++) {
  53659. for (var p = 0; p < pathArray.length; p++) {
  53660. var path = pathArray[p];
  53661. var l = path.length;
  53662. minlg = (minlg < l) ? minlg : l;
  53663. var j = 0;
  53664. while (j < minlg) {
  53665. positions[i] = path[j].x;
  53666. positions[i + 1] = path[j].y;
  53667. positions[i + 2] = path[j].z;
  53668. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53669. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53670. }
  53671. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53672. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53673. }
  53674. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53675. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53676. }
  53677. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53678. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53679. }
  53680. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53681. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53682. }
  53683. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53684. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53685. }
  53686. j++;
  53687. i += 3;
  53688. }
  53689. if (instance._closePath) {
  53690. positions[i] = path[0].x;
  53691. positions[i + 1] = path[0].y;
  53692. positions[i + 2] = path[0].z;
  53693. i += 3;
  53694. }
  53695. }
  53696. }
  53697. };
  53698. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53699. positionFunction(positions);
  53700. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53701. instance._boundingInfo.update(instance._worldMatrix);
  53702. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53703. if (options.colors) {
  53704. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53705. for (var c = 0; c < options.colors.length; c++) {
  53706. colors[c * 4] = options.colors[c].r;
  53707. colors[c * 4 + 1] = options.colors[c].g;
  53708. colors[c * 4 + 2] = options.colors[c].b;
  53709. colors[c * 4 + 3] = options.colors[c].a;
  53710. }
  53711. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53712. }
  53713. if (options.uvs) {
  53714. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53715. for (var i = 0; i < options.uvs.length; i++) {
  53716. uvs[i * 2] = options.uvs[i].x;
  53717. uvs[i * 2 + 1] = options.uvs[i].y;
  53718. }
  53719. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53720. }
  53721. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53722. var indices = instance.getIndices();
  53723. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53724. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53725. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53726. if (instance._closePath) {
  53727. var indexFirst = 0;
  53728. var indexLast = 0;
  53729. for (var p = 0; p < pathArray.length; p++) {
  53730. indexFirst = instance._idx[p] * 3;
  53731. if (p + 1 < pathArray.length) {
  53732. indexLast = (instance._idx[p + 1] - 1) * 3;
  53733. }
  53734. else {
  53735. indexLast = normals.length - 3;
  53736. }
  53737. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53738. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53739. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53740. normals[indexLast] = normals[indexFirst];
  53741. normals[indexLast + 1] = normals[indexFirst + 1];
  53742. normals[indexLast + 2] = normals[indexFirst + 2];
  53743. }
  53744. }
  53745. if (!(instance.areNormalsFrozen)) {
  53746. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53747. }
  53748. }
  53749. return instance;
  53750. }
  53751. else {
  53752. var ribbon = new BABYLON.Mesh(name, scene);
  53753. ribbon._originalBuilderSideOrientation = sideOrientation;
  53754. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53755. if (closePath) {
  53756. ribbon._idx = vertexData._idx;
  53757. }
  53758. ribbon._closePath = closePath;
  53759. ribbon._closeArray = closeArray;
  53760. vertexData.applyToMesh(ribbon, updatable);
  53761. return ribbon;
  53762. }
  53763. };
  53764. /**
  53765. * Creates a cylinder or a cone mesh.
  53766. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53767. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53768. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53769. * 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.
  53770. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53771. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53772. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53773. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53774. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53775. * 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).
  53776. * 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
  53777. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53778. * 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
  53779. * 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.
  53780. * If `enclose` is false, a ring surface is one element.
  53781. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53782. * 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
  53783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53784. * 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).
  53785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53787. */
  53788. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53789. var cylinder = new BABYLON.Mesh(name, scene);
  53790. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53791. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53792. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53793. vertexData.applyToMesh(cylinder, options.updatable);
  53794. return cylinder;
  53795. };
  53796. /**
  53797. * Creates a torus mesh.
  53798. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53799. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53800. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53801. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53803. * 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).
  53804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53806. */
  53807. MeshBuilder.CreateTorus = function (name, options, scene) {
  53808. var torus = new BABYLON.Mesh(name, scene);
  53809. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53810. torus._originalBuilderSideOrientation = options.sideOrientation;
  53811. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53812. vertexData.applyToMesh(torus, options.updatable);
  53813. return torus;
  53814. };
  53815. /**
  53816. * Creates a torus knot mesh.
  53817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53818. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53819. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53820. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53821. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53823. * 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).
  53824. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53826. */
  53827. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53828. var torusKnot = new BABYLON.Mesh(name, scene);
  53829. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53830. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53831. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53832. vertexData.applyToMesh(torusKnot, options.updatable);
  53833. return torusKnot;
  53834. };
  53835. /**
  53836. * Creates a line system mesh.
  53837. * A line system is a pool of many lines gathered in a single mesh.
  53838. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53839. * 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.
  53840. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53841. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53842. * 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
  53843. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53844. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53845. * 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
  53846. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53848. */
  53849. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53850. var instance = options.instance;
  53851. var lines = options.lines;
  53852. var colors = options.colors;
  53853. if (instance) {
  53854. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53855. var vertexColor;
  53856. var lineColors;
  53857. if (colors) {
  53858. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53859. }
  53860. var i = 0;
  53861. var c = 0;
  53862. for (var l = 0; l < lines.length; l++) {
  53863. var points = lines[l];
  53864. for (var p = 0; p < points.length; p++) {
  53865. positions[i] = points[p].x;
  53866. positions[i + 1] = points[p].y;
  53867. positions[i + 2] = points[p].z;
  53868. if (colors && vertexColor) {
  53869. lineColors = colors[l];
  53870. vertexColor[c] = lineColors[p].r;
  53871. vertexColor[c + 1] = lineColors[p].g;
  53872. vertexColor[c + 2] = lineColors[p].b;
  53873. vertexColor[c + 3] = lineColors[p].a;
  53874. c += 4;
  53875. }
  53876. i += 3;
  53877. }
  53878. }
  53879. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53880. if (colors && vertexColor) {
  53881. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  53882. }
  53883. return instance;
  53884. }
  53885. // line system creation
  53886. var useVertexColor = (colors) ? true : false;
  53887. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  53888. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  53889. vertexData.applyToMesh(lineSystem, options.updatable);
  53890. return lineSystem;
  53891. };
  53892. /**
  53893. * Creates a line mesh.
  53894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  53895. * 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.
  53896. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53897. * The parameter `points` is an array successive Vector3.
  53898. * 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
  53899. * The optional parameter `colors` is an array of successive Color4, one per line point.
  53900. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  53901. * When updating an instance, remember that only point positions can change, not the number of points.
  53902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53903. */
  53904. MeshBuilder.CreateLines = function (name, options, scene) {
  53905. if (scene === void 0) { scene = null; }
  53906. var colors = (options.colors) ? [options.colors] : null;
  53907. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  53908. return lines;
  53909. };
  53910. /**
  53911. * Creates a dashed line mesh.
  53912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  53913. * 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.
  53914. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53915. * The parameter `points` is an array successive Vector3.
  53916. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  53917. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  53918. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  53919. * 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
  53920. * When updating an instance, remember that only point positions can change, not the number of points.
  53921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53922. */
  53923. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  53924. if (scene === void 0) { scene = null; }
  53925. var points = options.points;
  53926. var instance = options.instance;
  53927. var gapSize = options.gapSize || 1;
  53928. var dashSize = options.dashSize || 3;
  53929. if (instance) {
  53930. var positionFunction = function (positions) {
  53931. var curvect = BABYLON.Vector3.Zero();
  53932. var nbSeg = positions.length / 6;
  53933. var lg = 0;
  53934. var nb = 0;
  53935. var shft = 0;
  53936. var dashshft = 0;
  53937. var curshft = 0;
  53938. var p = 0;
  53939. var i = 0;
  53940. var j = 0;
  53941. for (i = 0; i < points.length - 1; i++) {
  53942. points[i + 1].subtractToRef(points[i], curvect);
  53943. lg += curvect.length();
  53944. }
  53945. shft = lg / nbSeg;
  53946. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  53947. for (i = 0; i < points.length - 1; i++) {
  53948. points[i + 1].subtractToRef(points[i], curvect);
  53949. nb = Math.floor(curvect.length() / shft);
  53950. curvect.normalize();
  53951. j = 0;
  53952. while (j < nb && p < positions.length) {
  53953. curshft = shft * j;
  53954. positions[p] = points[i].x + curshft * curvect.x;
  53955. positions[p + 1] = points[i].y + curshft * curvect.y;
  53956. positions[p + 2] = points[i].z + curshft * curvect.z;
  53957. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  53958. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  53959. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  53960. p += 6;
  53961. j++;
  53962. }
  53963. }
  53964. while (p < positions.length) {
  53965. positions[p] = points[i].x;
  53966. positions[p + 1] = points[i].y;
  53967. positions[p + 2] = points[i].z;
  53968. p += 3;
  53969. }
  53970. };
  53971. instance.updateMeshPositions(positionFunction, false);
  53972. return instance;
  53973. }
  53974. // dashed lines creation
  53975. var dashedLines = new BABYLON.LinesMesh(name, scene);
  53976. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  53977. vertexData.applyToMesh(dashedLines, options.updatable);
  53978. dashedLines.dashSize = dashSize;
  53979. dashedLines.gapSize = gapSize;
  53980. return dashedLines;
  53981. };
  53982. /**
  53983. * Creates an extruded shape mesh.
  53984. * 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.
  53985. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  53986. *
  53987. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  53988. * 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
  53989. * extruded along the Z axis.
  53990. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  53991. * 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.
  53992. * The parameter `scale` (float, default 1) is the value to scale the shape.
  53993. * 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
  53994. * 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
  53995. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  53996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53997. * 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).
  53998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53999. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54001. */
  54002. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54003. if (scene === void 0) { scene = null; }
  54004. var path = options.path;
  54005. var shape = options.shape;
  54006. var scale = options.scale || 1;
  54007. var rotation = options.rotation || 0;
  54008. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54009. var updatable = options.updatable;
  54010. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54011. var instance = options.instance || null;
  54012. var invertUV = options.invertUV || false;
  54013. 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);
  54014. };
  54015. /**
  54016. * Creates an custom extruded shape mesh.
  54017. * 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.
  54018. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54019. *
  54020. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54021. * 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
  54022. * extruded along the Z axis.
  54023. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54024. * 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
  54025. * and the distance of this point from the begining of the path :
  54026. * ```javascript
  54027. * var rotationFunction = function(i, distance) {
  54028. * // do things
  54029. * return rotationValue; }
  54030. * ```
  54031. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54032. * 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
  54033. * and the distance of this point from the begining of the path :
  54034. * ```javascript
  54035. * var scaleFunction = function(i, distance) {
  54036. * // do things
  54037. * return scaleValue;}
  54038. * ```
  54039. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54040. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54041. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54042. * 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
  54043. * 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
  54044. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54046. * 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).
  54047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54048. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54050. */
  54051. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54052. var path = options.path;
  54053. var shape = options.shape;
  54054. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54055. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54056. var ribbonCloseArray = options.ribbonCloseArray || false;
  54057. var ribbonClosePath = options.ribbonClosePath || false;
  54058. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54059. var updatable = options.updatable;
  54060. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54061. var instance = options.instance;
  54062. var invertUV = options.invertUV || false;
  54063. 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);
  54064. };
  54065. /**
  54066. * Creates lathe mesh.
  54067. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54068. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54069. *
  54070. * 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
  54071. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54072. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54073. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54074. * 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.
  54075. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54076. * 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
  54077. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54078. * 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).
  54079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54080. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54082. */
  54083. MeshBuilder.CreateLathe = function (name, options, scene) {
  54084. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54085. var closed = (options.closed === undefined) ? true : options.closed;
  54086. var shape = options.shape;
  54087. var radius = options.radius || 1;
  54088. var tessellation = options.tessellation || 64;
  54089. var updatable = options.updatable;
  54090. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54091. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54092. var pi2 = Math.PI * 2;
  54093. var paths = new Array();
  54094. var invertUV = options.invertUV || false;
  54095. var i = 0;
  54096. var p = 0;
  54097. var step = pi2 / tessellation * arc;
  54098. var rotated;
  54099. var path = new Array();
  54100. ;
  54101. for (i = 0; i <= tessellation; i++) {
  54102. var path = [];
  54103. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54104. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54105. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54106. }
  54107. for (p = 0; p < shape.length; p++) {
  54108. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54109. path.push(rotated);
  54110. }
  54111. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54112. 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));
  54113. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54114. }
  54115. paths.push(path);
  54116. }
  54117. // lathe ribbon
  54118. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54119. return lathe;
  54120. };
  54121. /**
  54122. * Creates a plane mesh.
  54123. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54124. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54125. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54126. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54128. * 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).
  54129. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54131. */
  54132. MeshBuilder.CreatePlane = function (name, options, scene) {
  54133. var plane = new BABYLON.Mesh(name, scene);
  54134. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54135. plane._originalBuilderSideOrientation = options.sideOrientation;
  54136. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54137. vertexData.applyToMesh(plane, options.updatable);
  54138. if (options.sourcePlane) {
  54139. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54140. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54141. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54142. plane.rotate(vectorProduct, product);
  54143. }
  54144. return plane;
  54145. };
  54146. /**
  54147. * Creates a ground mesh.
  54148. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54149. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54150. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54152. */
  54153. MeshBuilder.CreateGround = function (name, options, scene) {
  54154. var ground = new BABYLON.GroundMesh(name, scene);
  54155. ground._setReady(false);
  54156. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54157. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54158. ground._width = options.width || 1;
  54159. ground._height = options.height || 1;
  54160. ground._maxX = ground._width / 2;
  54161. ground._maxZ = ground._height / 2;
  54162. ground._minX = -ground._maxX;
  54163. ground._minZ = -ground._maxZ;
  54164. var vertexData = BABYLON.VertexData.CreateGround(options);
  54165. vertexData.applyToMesh(ground, options.updatable);
  54166. ground._setReady(true);
  54167. return ground;
  54168. };
  54169. /**
  54170. * Creates a tiled ground mesh.
  54171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54172. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54173. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54174. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54175. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54176. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54177. * numbers of subdivisions on the ground width and height of each tile.
  54178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54179. */
  54180. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54181. var tiledGround = new BABYLON.Mesh(name, scene);
  54182. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54183. vertexData.applyToMesh(tiledGround, options.updatable);
  54184. return tiledGround;
  54185. };
  54186. /**
  54187. * Creates a ground mesh from a height map.
  54188. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54189. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54190. * The parameter `url` sets the URL of the height map image resource.
  54191. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54192. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54193. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54194. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54195. * 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.
  54196. * 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).
  54197. * This function is passed the newly built mesh :
  54198. * ```javascript
  54199. * function(mesh) { // do things
  54200. * return; }
  54201. * ```
  54202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54203. */
  54204. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54205. var width = options.width || 10.0;
  54206. var height = options.height || 10.0;
  54207. var subdivisions = options.subdivisions || 1 | 0;
  54208. var minHeight = options.minHeight || 0.0;
  54209. var maxHeight = options.maxHeight || 1.0;
  54210. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54211. var updatable = options.updatable;
  54212. var onReady = options.onReady;
  54213. var ground = new BABYLON.GroundMesh(name, scene);
  54214. ground._subdivisionsX = subdivisions;
  54215. ground._subdivisionsY = subdivisions;
  54216. ground._width = width;
  54217. ground._height = height;
  54218. ground._maxX = ground._width / 2.0;
  54219. ground._maxZ = ground._height / 2.0;
  54220. ground._minX = -ground._maxX;
  54221. ground._minZ = -ground._maxZ;
  54222. ground._setReady(false);
  54223. var onload = function (img) {
  54224. // Getting height map data
  54225. var canvas = document.createElement("canvas");
  54226. var context = canvas.getContext("2d");
  54227. if (!context) {
  54228. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54229. }
  54230. if (scene.isDisposed) {
  54231. return;
  54232. }
  54233. var bufferWidth = img.width;
  54234. var bufferHeight = img.height;
  54235. canvas.width = bufferWidth;
  54236. canvas.height = bufferHeight;
  54237. context.drawImage(img, 0, 0);
  54238. // Create VertexData from map data
  54239. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54240. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54241. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54242. width: width, height: height,
  54243. subdivisions: subdivisions,
  54244. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54245. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54246. });
  54247. vertexData.applyToMesh(ground, updatable);
  54248. ground._setReady(true);
  54249. //execute ready callback, if set
  54250. if (onReady) {
  54251. onReady(ground);
  54252. }
  54253. };
  54254. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54255. return ground;
  54256. };
  54257. /**
  54258. * Creates a polygon mesh.
  54259. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54260. * 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.
  54261. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54263. * 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).
  54264. * Remember you can only change the shape positions, not their number when updating a polygon.
  54265. */
  54266. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54267. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54268. var shape = options.shape;
  54269. var holes = options.holes || [];
  54270. var depth = options.depth || 0;
  54271. var contours = [];
  54272. var hole = [];
  54273. for (var i = 0; i < shape.length; i++) {
  54274. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54275. }
  54276. var epsilon = 0.00000001;
  54277. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54278. contours.pop();
  54279. }
  54280. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54281. for (var hNb = 0; hNb < holes.length; hNb++) {
  54282. hole = [];
  54283. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54284. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54285. }
  54286. polygonTriangulation.addHole(hole);
  54287. }
  54288. var polygon = polygonTriangulation.build(options.updatable, depth);
  54289. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54290. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54291. vertexData.applyToMesh(polygon, options.updatable);
  54292. return polygon;
  54293. };
  54294. ;
  54295. /**
  54296. * Creates an extruded polygon mesh, with depth in the Y direction.
  54297. * 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).
  54298. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54299. */
  54300. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54301. return MeshBuilder.CreatePolygon(name, options, scene);
  54302. };
  54303. ;
  54304. /**
  54305. * Creates a tube mesh.
  54306. * 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.
  54307. *
  54308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54309. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54310. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54311. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54312. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54313. * 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.
  54314. * It must return a radius value (positive float) :
  54315. * ```javascript
  54316. * var radiusFunction = function(i, distance) {
  54317. * // do things
  54318. * return radius; }
  54319. * ```
  54320. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54321. * 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
  54322. * 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
  54323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54324. * 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).
  54325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54326. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54328. */
  54329. MeshBuilder.CreateTube = function (name, options, scene) {
  54330. var path = options.path;
  54331. var instance = options.instance;
  54332. var radius = 1.0;
  54333. if (instance) {
  54334. radius = instance.radius;
  54335. }
  54336. if (options.radius !== undefined) {
  54337. radius = options.radius;
  54338. }
  54339. ;
  54340. var tessellation = options.tessellation || 64 | 0;
  54341. var radiusFunction = options.radiusFunction || null;
  54342. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54343. var invertUV = options.invertUV || false;
  54344. var updatable = options.updatable;
  54345. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54346. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54347. // tube geometry
  54348. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54349. var tangents = path3D.getTangents();
  54350. var normals = path3D.getNormals();
  54351. var distances = path3D.getDistances();
  54352. var pi2 = Math.PI * 2;
  54353. var step = pi2 / tessellation * arc;
  54354. var returnRadius = function () { return radius; };
  54355. var radiusFunctionFinal = radiusFunction || returnRadius;
  54356. var circlePath;
  54357. var rad;
  54358. var normal;
  54359. var rotated;
  54360. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54361. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54362. for (var i = 0; i < path.length; i++) {
  54363. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54364. circlePath = Array(); // current circle array
  54365. normal = normals[i]; // current normal
  54366. for (var t = 0; t < tessellation; t++) {
  54367. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54368. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54369. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54370. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54371. circlePath[t] = rotated;
  54372. }
  54373. circlePaths[index] = circlePath;
  54374. index++;
  54375. }
  54376. // cap
  54377. var capPath = function (nbPoints, pathIndex) {
  54378. var pointCap = Array();
  54379. for (var i = 0; i < nbPoints; i++) {
  54380. pointCap.push(path[pathIndex]);
  54381. }
  54382. return pointCap;
  54383. };
  54384. switch (cap) {
  54385. case BABYLON.Mesh.NO_CAP:
  54386. break;
  54387. case BABYLON.Mesh.CAP_START:
  54388. circlePaths[0] = capPath(tessellation, 0);
  54389. circlePaths[1] = circlePaths[2].slice(0);
  54390. break;
  54391. case BABYLON.Mesh.CAP_END:
  54392. circlePaths[index] = circlePaths[index - 1].slice(0);
  54393. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54394. break;
  54395. case BABYLON.Mesh.CAP_ALL:
  54396. circlePaths[0] = capPath(tessellation, 0);
  54397. circlePaths[1] = circlePaths[2].slice(0);
  54398. circlePaths[index] = circlePaths[index - 1].slice(0);
  54399. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54400. break;
  54401. default:
  54402. break;
  54403. }
  54404. return circlePaths;
  54405. };
  54406. var path3D;
  54407. var pathArray;
  54408. if (instance) {
  54409. var arc = options.arc || instance.arc;
  54410. path3D = (instance.path3D).update(path);
  54411. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54412. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54413. instance.path3D = path3D;
  54414. instance.pathArray = pathArray;
  54415. instance.arc = arc;
  54416. instance.radius = radius;
  54417. return instance;
  54418. }
  54419. // tube creation
  54420. path3D = new BABYLON.Path3D(path);
  54421. var newPathArray = new Array();
  54422. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54423. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54424. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54425. tube.pathArray = pathArray;
  54426. tube.path3D = path3D;
  54427. tube.tessellation = tessellation;
  54428. tube.cap = cap;
  54429. tube.arc = options.arc;
  54430. tube.radius = radius;
  54431. return tube;
  54432. };
  54433. /**
  54434. * Creates a polyhedron mesh.
  54435. *
  54436. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54437. * 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
  54438. * to choose the wanted type.
  54439. * The parameter `size` (positive float, default 1) sets the polygon size.
  54440. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54441. * 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`.
  54442. * 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
  54443. * 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)`).
  54444. * 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
  54445. * 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.
  54446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54447. * 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).
  54448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54450. */
  54451. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54452. var polyhedron = new BABYLON.Mesh(name, scene);
  54453. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54454. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54455. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54456. vertexData.applyToMesh(polyhedron, options.updatable);
  54457. return polyhedron;
  54458. };
  54459. /**
  54460. * Creates a decal mesh.
  54461. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54462. * 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.
  54463. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54464. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54465. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54466. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54467. */
  54468. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54469. var indices = sourceMesh.getIndices();
  54470. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54471. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54472. var position = options.position || BABYLON.Vector3.Zero();
  54473. var normal = options.normal || BABYLON.Vector3.Up();
  54474. var size = options.size || BABYLON.Vector3.One();
  54475. var angle = options.angle || 0;
  54476. // Getting correct rotation
  54477. if (!normal) {
  54478. var target = new BABYLON.Vector3(0, 0, 1);
  54479. var camera = sourceMesh.getScene().activeCamera;
  54480. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54481. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54482. }
  54483. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54484. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54485. var pitch = Math.atan2(normal.y, len);
  54486. // Matrix
  54487. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54488. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54489. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54490. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54491. var vertexData = new BABYLON.VertexData();
  54492. vertexData.indices = [];
  54493. vertexData.positions = [];
  54494. vertexData.normals = [];
  54495. vertexData.uvs = [];
  54496. var currentVertexDataIndex = 0;
  54497. var extractDecalVector3 = function (indexId) {
  54498. var result = new BABYLON.PositionNormalVertex();
  54499. if (!indices || !positions || !normals) {
  54500. return result;
  54501. }
  54502. var vertexId = indices[indexId];
  54503. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54504. // Send vector to decal local world
  54505. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54506. // Get normal
  54507. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54508. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54509. return result;
  54510. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54511. var clip = function (vertices, axis) {
  54512. if (vertices.length === 0) {
  54513. return vertices;
  54514. }
  54515. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54516. var clipVertices = function (v0, v1) {
  54517. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54518. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54519. };
  54520. var result = new Array();
  54521. for (var index = 0; index < vertices.length; index += 3) {
  54522. var v1Out;
  54523. var v2Out;
  54524. var v3Out;
  54525. var total = 0;
  54526. var nV1 = null;
  54527. var nV2 = null;
  54528. var nV3 = null;
  54529. var nV4 = null;
  54530. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54531. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54532. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54533. v1Out = d1 > 0;
  54534. v2Out = d2 > 0;
  54535. v3Out = d3 > 0;
  54536. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54537. switch (total) {
  54538. case 0:
  54539. result.push(vertices[index]);
  54540. result.push(vertices[index + 1]);
  54541. result.push(vertices[index + 2]);
  54542. break;
  54543. case 1:
  54544. if (v1Out) {
  54545. nV1 = vertices[index + 1];
  54546. nV2 = vertices[index + 2];
  54547. nV3 = clipVertices(vertices[index], nV1);
  54548. nV4 = clipVertices(vertices[index], nV2);
  54549. }
  54550. if (v2Out) {
  54551. nV1 = vertices[index];
  54552. nV2 = vertices[index + 2];
  54553. nV3 = clipVertices(vertices[index + 1], nV1);
  54554. nV4 = clipVertices(vertices[index + 1], nV2);
  54555. result.push(nV3);
  54556. result.push(nV2.clone());
  54557. result.push(nV1.clone());
  54558. result.push(nV2.clone());
  54559. result.push(nV3.clone());
  54560. result.push(nV4);
  54561. break;
  54562. }
  54563. if (v3Out) {
  54564. nV1 = vertices[index];
  54565. nV2 = vertices[index + 1];
  54566. nV3 = clipVertices(vertices[index + 2], nV1);
  54567. nV4 = clipVertices(vertices[index + 2], nV2);
  54568. }
  54569. if (nV1 && nV2 && nV3 && nV4) {
  54570. result.push(nV1.clone());
  54571. result.push(nV2.clone());
  54572. result.push(nV3);
  54573. result.push(nV4);
  54574. result.push(nV3.clone());
  54575. result.push(nV2.clone());
  54576. }
  54577. break;
  54578. case 2:
  54579. if (!v1Out) {
  54580. nV1 = vertices[index].clone();
  54581. nV2 = clipVertices(nV1, vertices[index + 1]);
  54582. nV3 = clipVertices(nV1, vertices[index + 2]);
  54583. result.push(nV1);
  54584. result.push(nV2);
  54585. result.push(nV3);
  54586. }
  54587. if (!v2Out) {
  54588. nV1 = vertices[index + 1].clone();
  54589. nV2 = clipVertices(nV1, vertices[index + 2]);
  54590. nV3 = clipVertices(nV1, vertices[index]);
  54591. result.push(nV1);
  54592. result.push(nV2);
  54593. result.push(nV3);
  54594. }
  54595. if (!v3Out) {
  54596. nV1 = vertices[index + 2].clone();
  54597. nV2 = clipVertices(nV1, vertices[index]);
  54598. nV3 = clipVertices(nV1, vertices[index + 1]);
  54599. result.push(nV1);
  54600. result.push(nV2);
  54601. result.push(nV3);
  54602. }
  54603. break;
  54604. case 3:
  54605. break;
  54606. }
  54607. }
  54608. return result;
  54609. };
  54610. for (var index = 0; index < indices.length; index += 3) {
  54611. var faceVertices = new Array();
  54612. faceVertices.push(extractDecalVector3(index));
  54613. faceVertices.push(extractDecalVector3(index + 1));
  54614. faceVertices.push(extractDecalVector3(index + 2));
  54615. // Clip
  54616. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54617. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54618. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54619. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54620. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54621. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54622. if (faceVertices.length === 0) {
  54623. continue;
  54624. }
  54625. // Add UVs and get back to world
  54626. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54627. var vertex = faceVertices[vIndex];
  54628. //TODO check for Int32Array | Uint32Array | Uint16Array
  54629. vertexData.indices.push(currentVertexDataIndex);
  54630. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54631. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54632. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54633. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54634. currentVertexDataIndex++;
  54635. }
  54636. }
  54637. // Return mesh
  54638. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54639. vertexData.applyToMesh(decal);
  54640. decal.position = position.clone();
  54641. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54642. return decal;
  54643. };
  54644. // Privates
  54645. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54646. // extrusion geometry
  54647. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54648. var tangents = path3D.getTangents();
  54649. var normals = path3D.getNormals();
  54650. var binormals = path3D.getBinormals();
  54651. var distances = path3D.getDistances();
  54652. var angle = 0;
  54653. var returnScale = function () { return scale !== null ? scale : 1; };
  54654. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54655. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54656. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54657. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54658. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54659. for (var i = 0; i < curve.length; i++) {
  54660. var shapePath = new Array();
  54661. var angleStep = rotate(i, distances[i]);
  54662. var scaleRatio = scl(i, distances[i]);
  54663. for (var p = 0; p < shape.length; p++) {
  54664. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54665. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54666. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54667. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54668. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54669. shapePath[p] = rotated;
  54670. }
  54671. shapePaths[index] = shapePath;
  54672. angle += angleStep;
  54673. index++;
  54674. }
  54675. // cap
  54676. var capPath = function (shapePath) {
  54677. var pointCap = Array();
  54678. var barycenter = BABYLON.Vector3.Zero();
  54679. var i;
  54680. for (i = 0; i < shapePath.length; i++) {
  54681. barycenter.addInPlace(shapePath[i]);
  54682. }
  54683. barycenter.scaleInPlace(1.0 / shapePath.length);
  54684. for (i = 0; i < shapePath.length; i++) {
  54685. pointCap.push(barycenter);
  54686. }
  54687. return pointCap;
  54688. };
  54689. switch (cap) {
  54690. case BABYLON.Mesh.NO_CAP:
  54691. break;
  54692. case BABYLON.Mesh.CAP_START:
  54693. shapePaths[0] = capPath(shapePaths[2]);
  54694. shapePaths[1] = shapePaths[2];
  54695. break;
  54696. case BABYLON.Mesh.CAP_END:
  54697. shapePaths[index] = shapePaths[index - 1];
  54698. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54699. break;
  54700. case BABYLON.Mesh.CAP_ALL:
  54701. shapePaths[0] = capPath(shapePaths[2]);
  54702. shapePaths[1] = shapePaths[2];
  54703. shapePaths[index] = shapePaths[index - 1];
  54704. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54705. break;
  54706. default:
  54707. break;
  54708. }
  54709. return shapePaths;
  54710. };
  54711. var path3D;
  54712. var pathArray;
  54713. if (instance) {
  54714. path3D = (instance.path3D).update(curve);
  54715. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54716. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54717. return instance;
  54718. }
  54719. // extruded shape creation
  54720. path3D = new BABYLON.Path3D(curve);
  54721. var newShapePaths = new Array();
  54722. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54723. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54724. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54725. extrudedGeneric.pathArray = pathArray;
  54726. extrudedGeneric.path3D = path3D;
  54727. extrudedGeneric.cap = cap;
  54728. return extrudedGeneric;
  54729. };
  54730. return MeshBuilder;
  54731. }());
  54732. BABYLON.MeshBuilder = MeshBuilder;
  54733. })(BABYLON || (BABYLON = {}));
  54734. //# sourceMappingURL=babylon.meshBuilder.js.map
  54735. var BABYLON;
  54736. (function (BABYLON) {
  54737. var AudioEngine = /** @class */ (function () {
  54738. function AudioEngine() {
  54739. this._audioContext = null;
  54740. this._audioContextInitialized = false;
  54741. this.canUseWebAudio = false;
  54742. this.WarnedWebAudioUnsupported = false;
  54743. this.unlocked = false;
  54744. this.isMP3supported = false;
  54745. this.isOGGsupported = false;
  54746. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54747. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54748. this.canUseWebAudio = true;
  54749. }
  54750. var audioElem = document.createElement('audio');
  54751. try {
  54752. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54753. this.isMP3supported = true;
  54754. }
  54755. }
  54756. catch (e) {
  54757. // protect error during capability check.
  54758. }
  54759. try {
  54760. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54761. this.isOGGsupported = true;
  54762. }
  54763. }
  54764. catch (e) {
  54765. // protect error during capability check.
  54766. }
  54767. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54768. this._unlockiOSaudio();
  54769. }
  54770. else {
  54771. this.unlocked = true;
  54772. }
  54773. }
  54774. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54775. get: function () {
  54776. if (!this._audioContextInitialized) {
  54777. this._initializeAudioContext();
  54778. }
  54779. return this._audioContext;
  54780. },
  54781. enumerable: true,
  54782. configurable: true
  54783. });
  54784. AudioEngine.prototype._unlockiOSaudio = function () {
  54785. var _this = this;
  54786. var unlockaudio = function () {
  54787. if (!_this.audioContext) {
  54788. return;
  54789. }
  54790. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54791. var source = _this.audioContext.createBufferSource();
  54792. source.buffer = buffer;
  54793. source.connect(_this.audioContext.destination);
  54794. source.start(0);
  54795. setTimeout(function () {
  54796. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54797. _this.unlocked = true;
  54798. window.removeEventListener('touchend', unlockaudio, false);
  54799. if (_this.onAudioUnlocked) {
  54800. _this.onAudioUnlocked();
  54801. }
  54802. }
  54803. }, 0);
  54804. };
  54805. window.addEventListener('touchend', unlockaudio, false);
  54806. };
  54807. AudioEngine.prototype._initializeAudioContext = function () {
  54808. try {
  54809. if (this.canUseWebAudio) {
  54810. this._audioContext = new AudioContext();
  54811. // create a global volume gain node
  54812. this.masterGain = this._audioContext.createGain();
  54813. this.masterGain.gain.value = 1;
  54814. this.masterGain.connect(this._audioContext.destination);
  54815. this._audioContextInitialized = true;
  54816. }
  54817. }
  54818. catch (e) {
  54819. this.canUseWebAudio = false;
  54820. BABYLON.Tools.Error("Web Audio: " + e.message);
  54821. }
  54822. };
  54823. AudioEngine.prototype.dispose = function () {
  54824. if (this.canUseWebAudio && this._audioContextInitialized) {
  54825. if (this._connectedAnalyser && this._audioContext) {
  54826. this._connectedAnalyser.stopDebugCanvas();
  54827. this._connectedAnalyser.dispose();
  54828. this.masterGain.disconnect();
  54829. this.masterGain.connect(this._audioContext.destination);
  54830. this._connectedAnalyser = null;
  54831. }
  54832. this.masterGain.gain.value = 1;
  54833. }
  54834. this.WarnedWebAudioUnsupported = false;
  54835. };
  54836. AudioEngine.prototype.getGlobalVolume = function () {
  54837. if (this.canUseWebAudio && this._audioContextInitialized) {
  54838. return this.masterGain.gain.value;
  54839. }
  54840. else {
  54841. return -1;
  54842. }
  54843. };
  54844. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54845. if (this.canUseWebAudio && this._audioContextInitialized) {
  54846. this.masterGain.gain.value = newVolume;
  54847. }
  54848. };
  54849. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54850. if (this._connectedAnalyser) {
  54851. this._connectedAnalyser.stopDebugCanvas();
  54852. }
  54853. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54854. this._connectedAnalyser = analyser;
  54855. this.masterGain.disconnect();
  54856. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54857. }
  54858. };
  54859. return AudioEngine;
  54860. }());
  54861. BABYLON.AudioEngine = AudioEngine;
  54862. })(BABYLON || (BABYLON = {}));
  54863. //# sourceMappingURL=babylon.audioEngine.js.map
  54864. var BABYLON;
  54865. (function (BABYLON) {
  54866. var Sound = /** @class */ (function () {
  54867. /**
  54868. * Create a sound and attach it to a scene
  54869. * @param name Name of your sound
  54870. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54871. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54872. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54873. */
  54874. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54875. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  54876. var _this = this;
  54877. this.autoplay = false;
  54878. this.loop = false;
  54879. this.useCustomAttenuation = false;
  54880. this.spatialSound = false;
  54881. this.refDistance = 1;
  54882. this.rolloffFactor = 1;
  54883. this.maxDistance = 100;
  54884. this.distanceModel = "linear";
  54885. this._panningModel = "equalpower";
  54886. this._playbackRate = 1;
  54887. this._streaming = false;
  54888. this._startTime = 0;
  54889. this._startOffset = 0;
  54890. this._position = BABYLON.Vector3.Zero();
  54891. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  54892. this._volume = 1;
  54893. this._isReadyToPlay = false;
  54894. this.isPlaying = false;
  54895. this.isPaused = false;
  54896. this._isDirectional = false;
  54897. // Used if you'd like to create a directional sound.
  54898. // If not set, the sound will be omnidirectional
  54899. this._coneInnerAngle = 360;
  54900. this._coneOuterAngle = 360;
  54901. this._coneOuterGain = 0;
  54902. this._isOutputConnected = false;
  54903. this._urlType = "Unknown";
  54904. this.name = name;
  54905. this._scene = scene;
  54906. this._readyToPlayCallback = readyToPlayCallback;
  54907. // Default custom attenuation function is a linear attenuation
  54908. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  54909. if (currentDistance < maxDistance) {
  54910. return currentVolume * (1 - currentDistance / maxDistance);
  54911. }
  54912. else {
  54913. return 0;
  54914. }
  54915. };
  54916. if (options) {
  54917. this.autoplay = options.autoplay || false;
  54918. this.loop = options.loop || false;
  54919. // if volume === 0, we need another way to check this option
  54920. if (options.volume !== undefined) {
  54921. this._volume = options.volume;
  54922. }
  54923. this.spatialSound = options.spatialSound || false;
  54924. this.maxDistance = options.maxDistance || 100;
  54925. this.useCustomAttenuation = options.useCustomAttenuation || false;
  54926. this.rolloffFactor = options.rolloffFactor || 1;
  54927. this.refDistance = options.refDistance || 1;
  54928. this.distanceModel = options.distanceModel || "linear";
  54929. this._playbackRate = options.playbackRate || 1;
  54930. this._streaming = options.streaming || false;
  54931. }
  54932. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54933. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  54934. this._soundGain.gain.value = this._volume;
  54935. this._inputAudioNode = this._soundGain;
  54936. this._ouputAudioNode = this._soundGain;
  54937. if (this.spatialSound) {
  54938. this._createSpatialParameters();
  54939. }
  54940. this._scene.mainSoundTrack.AddSound(this);
  54941. var validParameter = true;
  54942. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  54943. if (urlOrArrayBuffer) {
  54944. if (typeof (urlOrArrayBuffer) === "string")
  54945. this._urlType = "String";
  54946. if (Array.isArray(urlOrArrayBuffer))
  54947. this._urlType = "Array";
  54948. if (urlOrArrayBuffer instanceof ArrayBuffer)
  54949. this._urlType = "ArrayBuffer";
  54950. var urls = [];
  54951. var codecSupportedFound = false;
  54952. switch (this._urlType) {
  54953. case "ArrayBuffer":
  54954. if (urlOrArrayBuffer.byteLength > 0) {
  54955. codecSupportedFound = true;
  54956. this._soundLoaded(urlOrArrayBuffer);
  54957. }
  54958. break;
  54959. case "String":
  54960. urls.push(urlOrArrayBuffer);
  54961. case "Array":
  54962. if (urls.length === 0)
  54963. urls = urlOrArrayBuffer;
  54964. // If we found a supported format, we load it immediately and stop the loop
  54965. for (var i = 0; i < urls.length; i++) {
  54966. var url = urls[i];
  54967. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  54968. codecSupportedFound = true;
  54969. }
  54970. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  54971. codecSupportedFound = true;
  54972. }
  54973. if (url.indexOf(".wav", url.length - 4) !== -1) {
  54974. codecSupportedFound = true;
  54975. }
  54976. if (url.indexOf("blob:") !== -1) {
  54977. codecSupportedFound = true;
  54978. }
  54979. if (codecSupportedFound) {
  54980. // Loading sound using XHR2
  54981. if (!this._streaming) {
  54982. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  54983. }
  54984. else {
  54985. this._htmlAudioElement = new Audio(url);
  54986. this._htmlAudioElement.controls = false;
  54987. this._htmlAudioElement.loop = this.loop;
  54988. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  54989. this._htmlAudioElement.preload = "auto";
  54990. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  54991. _this._isReadyToPlay = true;
  54992. if (_this.autoplay) {
  54993. _this.play();
  54994. }
  54995. if (_this._readyToPlayCallback) {
  54996. _this._readyToPlayCallback();
  54997. }
  54998. });
  54999. document.body.appendChild(this._htmlAudioElement);
  55000. }
  55001. break;
  55002. }
  55003. }
  55004. break;
  55005. default:
  55006. validParameter = false;
  55007. break;
  55008. }
  55009. if (!validParameter) {
  55010. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55011. }
  55012. else {
  55013. if (!codecSupportedFound) {
  55014. this._isReadyToPlay = true;
  55015. // Simulating a ready to play event to avoid breaking code path
  55016. if (this._readyToPlayCallback) {
  55017. window.setTimeout(function () {
  55018. if (_this._readyToPlayCallback) {
  55019. _this._readyToPlayCallback();
  55020. }
  55021. }, 1000);
  55022. }
  55023. }
  55024. }
  55025. }
  55026. }
  55027. else {
  55028. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55029. this._scene.mainSoundTrack.AddSound(this);
  55030. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55031. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55032. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55033. }
  55034. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55035. if (this._readyToPlayCallback) {
  55036. window.setTimeout(function () {
  55037. if (_this._readyToPlayCallback) {
  55038. _this._readyToPlayCallback();
  55039. }
  55040. }, 1000);
  55041. }
  55042. }
  55043. }
  55044. Sound.prototype.dispose = function () {
  55045. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55046. if (this.isPlaying) {
  55047. this.stop();
  55048. }
  55049. this._isReadyToPlay = false;
  55050. if (this.soundTrackId === -1) {
  55051. this._scene.mainSoundTrack.RemoveSound(this);
  55052. }
  55053. else {
  55054. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55055. }
  55056. if (this._soundGain) {
  55057. this._soundGain.disconnect();
  55058. this._soundGain = null;
  55059. }
  55060. if (this._soundPanner) {
  55061. this._soundPanner.disconnect();
  55062. this._soundPanner = null;
  55063. }
  55064. if (this._soundSource) {
  55065. this._soundSource.disconnect();
  55066. this._soundSource = null;
  55067. }
  55068. this._audioBuffer = null;
  55069. if (this._htmlAudioElement) {
  55070. this._htmlAudioElement.pause();
  55071. this._htmlAudioElement.src = "";
  55072. document.body.removeChild(this._htmlAudioElement);
  55073. }
  55074. if (this._connectedMesh && this._registerFunc) {
  55075. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55076. this._connectedMesh = null;
  55077. }
  55078. }
  55079. };
  55080. Sound.prototype.isReady = function () {
  55081. return this._isReadyToPlay;
  55082. };
  55083. Sound.prototype._soundLoaded = function (audioData) {
  55084. var _this = this;
  55085. if (!BABYLON.Engine.audioEngine.audioContext) {
  55086. return;
  55087. }
  55088. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55089. _this._audioBuffer = buffer;
  55090. _this._isReadyToPlay = true;
  55091. if (_this.autoplay) {
  55092. _this.play();
  55093. }
  55094. if (_this._readyToPlayCallback) {
  55095. _this._readyToPlayCallback();
  55096. }
  55097. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55098. };
  55099. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55101. this._audioBuffer = audioBuffer;
  55102. this._isReadyToPlay = true;
  55103. }
  55104. };
  55105. Sound.prototype.updateOptions = function (options) {
  55106. if (options) {
  55107. this.loop = options.loop || this.loop;
  55108. this.maxDistance = options.maxDistance || this.maxDistance;
  55109. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55110. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55111. this.refDistance = options.refDistance || this.refDistance;
  55112. this.distanceModel = options.distanceModel || this.distanceModel;
  55113. this._playbackRate = options.playbackRate || this._playbackRate;
  55114. this._updateSpatialParameters();
  55115. if (this.isPlaying) {
  55116. if (this._streaming) {
  55117. this._htmlAudioElement.playbackRate = this._playbackRate;
  55118. }
  55119. else {
  55120. if (this._soundSource) {
  55121. this._soundSource.playbackRate.value = this._playbackRate;
  55122. }
  55123. }
  55124. }
  55125. }
  55126. };
  55127. Sound.prototype._createSpatialParameters = function () {
  55128. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55129. if (this._scene.headphone) {
  55130. this._panningModel = "HRTF";
  55131. }
  55132. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55133. this._updateSpatialParameters();
  55134. this._soundPanner.connect(this._ouputAudioNode);
  55135. this._inputAudioNode = this._soundPanner;
  55136. }
  55137. };
  55138. Sound.prototype._updateSpatialParameters = function () {
  55139. if (this.spatialSound && this._soundPanner) {
  55140. if (this.useCustomAttenuation) {
  55141. // Tricks to disable in a way embedded Web Audio attenuation
  55142. this._soundPanner.distanceModel = "linear";
  55143. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55144. this._soundPanner.refDistance = 1;
  55145. this._soundPanner.rolloffFactor = 1;
  55146. this._soundPanner.panningModel = this._panningModel;
  55147. }
  55148. else {
  55149. this._soundPanner.distanceModel = this.distanceModel;
  55150. this._soundPanner.maxDistance = this.maxDistance;
  55151. this._soundPanner.refDistance = this.refDistance;
  55152. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55153. this._soundPanner.panningModel = this._panningModel;
  55154. }
  55155. }
  55156. };
  55157. Sound.prototype.switchPanningModelToHRTF = function () {
  55158. this._panningModel = "HRTF";
  55159. this._switchPanningModel();
  55160. };
  55161. Sound.prototype.switchPanningModelToEqualPower = function () {
  55162. this._panningModel = "equalpower";
  55163. this._switchPanningModel();
  55164. };
  55165. Sound.prototype._switchPanningModel = function () {
  55166. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55167. this._soundPanner.panningModel = this._panningModel;
  55168. }
  55169. };
  55170. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55171. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55172. if (this._isOutputConnected) {
  55173. this._ouputAudioNode.disconnect();
  55174. }
  55175. this._ouputAudioNode.connect(soundTrackAudioNode);
  55176. this._isOutputConnected = true;
  55177. }
  55178. };
  55179. /**
  55180. * Transform this sound into a directional source
  55181. * @param coneInnerAngle Size of the inner cone in degree
  55182. * @param coneOuterAngle Size of the outer cone in degree
  55183. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55184. */
  55185. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55186. if (coneOuterAngle < coneInnerAngle) {
  55187. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55188. return;
  55189. }
  55190. this._coneInnerAngle = coneInnerAngle;
  55191. this._coneOuterAngle = coneOuterAngle;
  55192. this._coneOuterGain = coneOuterGain;
  55193. this._isDirectional = true;
  55194. if (this.isPlaying && this.loop) {
  55195. this.stop();
  55196. this.play();
  55197. }
  55198. };
  55199. Sound.prototype.setPosition = function (newPosition) {
  55200. this._position = newPosition;
  55201. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55202. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55203. }
  55204. };
  55205. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55206. this._localDirection = newLocalDirection;
  55207. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55208. this._updateDirection();
  55209. }
  55210. };
  55211. Sound.prototype._updateDirection = function () {
  55212. if (!this._connectedMesh || !this._soundPanner) {
  55213. return;
  55214. }
  55215. var mat = this._connectedMesh.getWorldMatrix();
  55216. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55217. direction.normalize();
  55218. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55219. };
  55220. Sound.prototype.updateDistanceFromListener = function () {
  55221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55222. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55223. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55224. }
  55225. };
  55226. Sound.prototype.setAttenuationFunction = function (callback) {
  55227. this._customAttenuationFunction = callback;
  55228. };
  55229. /**
  55230. * Play the sound
  55231. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55232. * @param offset (optional) Start the sound setting it at a specific time
  55233. */
  55234. Sound.prototype.play = function (time, offset) {
  55235. var _this = this;
  55236. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55237. try {
  55238. if (this._startOffset < 0) {
  55239. time = -this._startOffset;
  55240. this._startOffset = 0;
  55241. }
  55242. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55243. if (!this._soundSource || !this._streamingSource) {
  55244. if (this.spatialSound && this._soundPanner) {
  55245. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55246. if (this._isDirectional) {
  55247. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55248. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55249. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55250. if (this._connectedMesh) {
  55251. this._updateDirection();
  55252. }
  55253. else {
  55254. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55255. }
  55256. }
  55257. }
  55258. }
  55259. if (this._streaming) {
  55260. if (!this._streamingSource) {
  55261. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55262. this._htmlAudioElement.onended = function () { _this._onended(); };
  55263. this._htmlAudioElement.playbackRate = this._playbackRate;
  55264. }
  55265. this._streamingSource.disconnect();
  55266. this._streamingSource.connect(this._inputAudioNode);
  55267. this._htmlAudioElement.play();
  55268. }
  55269. else {
  55270. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55271. this._soundSource.buffer = this._audioBuffer;
  55272. this._soundSource.connect(this._inputAudioNode);
  55273. this._soundSource.loop = this.loop;
  55274. this._soundSource.playbackRate.value = this._playbackRate;
  55275. this._soundSource.onended = function () { _this._onended(); };
  55276. if (this._soundSource.buffer) {
  55277. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55278. }
  55279. }
  55280. this._startTime = startTime;
  55281. this.isPlaying = true;
  55282. this.isPaused = false;
  55283. }
  55284. catch (ex) {
  55285. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55286. }
  55287. }
  55288. };
  55289. Sound.prototype._onended = function () {
  55290. this.isPlaying = false;
  55291. if (this.onended) {
  55292. this.onended();
  55293. }
  55294. };
  55295. /**
  55296. * Stop the sound
  55297. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55298. */
  55299. Sound.prototype.stop = function (time) {
  55300. if (this.isPlaying) {
  55301. if (this._streaming) {
  55302. this._htmlAudioElement.pause();
  55303. // Test needed for Firefox or it will generate an Invalid State Error
  55304. if (this._htmlAudioElement.currentTime > 0) {
  55305. this._htmlAudioElement.currentTime = 0;
  55306. }
  55307. }
  55308. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55309. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55310. this._soundSource.stop(stopTime);
  55311. this._soundSource.onended = function () { };
  55312. if (!this.isPaused) {
  55313. this._startOffset = 0;
  55314. }
  55315. }
  55316. this.isPlaying = false;
  55317. }
  55318. };
  55319. Sound.prototype.pause = function () {
  55320. if (this.isPlaying) {
  55321. this.isPaused = true;
  55322. if (this._streaming) {
  55323. this._htmlAudioElement.pause();
  55324. }
  55325. else if (BABYLON.Engine.audioEngine.audioContext) {
  55326. this.stop(0);
  55327. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55328. }
  55329. }
  55330. };
  55331. Sound.prototype.setVolume = function (newVolume, time) {
  55332. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55333. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55334. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55335. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55336. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55337. }
  55338. else {
  55339. this._soundGain.gain.value = newVolume;
  55340. }
  55341. }
  55342. this._volume = newVolume;
  55343. };
  55344. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55345. this._playbackRate = newPlaybackRate;
  55346. if (this.isPlaying) {
  55347. if (this._streaming) {
  55348. this._htmlAudioElement.playbackRate = this._playbackRate;
  55349. }
  55350. else if (this._soundSource) {
  55351. this._soundSource.playbackRate.value = this._playbackRate;
  55352. }
  55353. }
  55354. };
  55355. Sound.prototype.getVolume = function () {
  55356. return this._volume;
  55357. };
  55358. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55359. var _this = this;
  55360. if (this._connectedMesh && this._registerFunc) {
  55361. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55362. this._registerFunc = null;
  55363. }
  55364. this._connectedMesh = meshToConnectTo;
  55365. if (!this.spatialSound) {
  55366. this.spatialSound = true;
  55367. this._createSpatialParameters();
  55368. if (this.isPlaying && this.loop) {
  55369. this.stop();
  55370. this.play();
  55371. }
  55372. }
  55373. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55374. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55375. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55376. };
  55377. Sound.prototype.detachFromMesh = function () {
  55378. if (this._connectedMesh && this._registerFunc) {
  55379. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55380. this._registerFunc = null;
  55381. this._connectedMesh = null;
  55382. }
  55383. };
  55384. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55385. if (!node.getBoundingInfo) {
  55386. return;
  55387. }
  55388. var mesh = node;
  55389. var boundingInfo = mesh.getBoundingInfo();
  55390. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55391. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55392. this._updateDirection();
  55393. }
  55394. };
  55395. Sound.prototype.clone = function () {
  55396. var _this = this;
  55397. if (!this._streaming) {
  55398. var setBufferAndRun = function () {
  55399. if (_this._isReadyToPlay) {
  55400. clonedSound._audioBuffer = _this.getAudioBuffer();
  55401. clonedSound._isReadyToPlay = true;
  55402. if (clonedSound.autoplay) {
  55403. clonedSound.play();
  55404. }
  55405. }
  55406. else {
  55407. window.setTimeout(setBufferAndRun, 300);
  55408. }
  55409. };
  55410. var currentOptions = {
  55411. autoplay: this.autoplay, loop: this.loop,
  55412. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55413. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55414. refDistance: this.refDistance, distanceModel: this.distanceModel
  55415. };
  55416. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55417. if (this.useCustomAttenuation) {
  55418. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55419. }
  55420. clonedSound.setPosition(this._position);
  55421. clonedSound.setPlaybackRate(this._playbackRate);
  55422. setBufferAndRun();
  55423. return clonedSound;
  55424. }
  55425. else {
  55426. return null;
  55427. }
  55428. };
  55429. Sound.prototype.getAudioBuffer = function () {
  55430. return this._audioBuffer;
  55431. };
  55432. Sound.prototype.serialize = function () {
  55433. var serializationObject = {
  55434. name: this.name,
  55435. url: this.name,
  55436. autoplay: this.autoplay,
  55437. loop: this.loop,
  55438. volume: this._volume,
  55439. spatialSound: this.spatialSound,
  55440. maxDistance: this.maxDistance,
  55441. rolloffFactor: this.rolloffFactor,
  55442. refDistance: this.refDistance,
  55443. distanceModel: this.distanceModel,
  55444. playbackRate: this._playbackRate,
  55445. panningModel: this._panningModel,
  55446. soundTrackId: this.soundTrackId
  55447. };
  55448. if (this.spatialSound) {
  55449. if (this._connectedMesh)
  55450. serializationObject.connectedMeshId = this._connectedMesh.id;
  55451. serializationObject.position = this._position.asArray();
  55452. serializationObject.refDistance = this.refDistance;
  55453. serializationObject.distanceModel = this.distanceModel;
  55454. serializationObject.isDirectional = this._isDirectional;
  55455. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55456. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55457. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55458. serializationObject.coneOuterGain = this._coneOuterGain;
  55459. }
  55460. return serializationObject;
  55461. };
  55462. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55463. var soundName = parsedSound.name;
  55464. var soundUrl;
  55465. if (parsedSound.url) {
  55466. soundUrl = rootUrl + parsedSound.url;
  55467. }
  55468. else {
  55469. soundUrl = rootUrl + soundName;
  55470. }
  55471. var options = {
  55472. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55473. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55474. rolloffFactor: parsedSound.rolloffFactor,
  55475. refDistance: parsedSound.refDistance,
  55476. distanceModel: parsedSound.distanceModel,
  55477. playbackRate: parsedSound.playbackRate
  55478. };
  55479. var newSound;
  55480. if (!sourceSound) {
  55481. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55482. scene._addPendingData(newSound);
  55483. }
  55484. else {
  55485. var setBufferAndRun = function () {
  55486. if (sourceSound._isReadyToPlay) {
  55487. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55488. newSound._isReadyToPlay = true;
  55489. if (newSound.autoplay) {
  55490. newSound.play();
  55491. }
  55492. }
  55493. else {
  55494. window.setTimeout(setBufferAndRun, 300);
  55495. }
  55496. };
  55497. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55498. setBufferAndRun();
  55499. }
  55500. if (parsedSound.position) {
  55501. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55502. newSound.setPosition(soundPosition);
  55503. }
  55504. if (parsedSound.isDirectional) {
  55505. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55506. if (parsedSound.localDirectionToMesh) {
  55507. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55508. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55509. }
  55510. }
  55511. if (parsedSound.connectedMeshId) {
  55512. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55513. if (connectedMesh) {
  55514. newSound.attachToMesh(connectedMesh);
  55515. }
  55516. }
  55517. return newSound;
  55518. };
  55519. return Sound;
  55520. }());
  55521. BABYLON.Sound = Sound;
  55522. })(BABYLON || (BABYLON = {}));
  55523. //# sourceMappingURL=babylon.sound.js.map
  55524. var BABYLON;
  55525. (function (BABYLON) {
  55526. var SoundTrack = /** @class */ (function () {
  55527. function SoundTrack(scene, options) {
  55528. this.id = -1;
  55529. this._isMainTrack = false;
  55530. this._isInitialized = false;
  55531. this._scene = scene;
  55532. this.soundCollection = new Array();
  55533. this._options = options;
  55534. if (!this._isMainTrack) {
  55535. this._scene.soundTracks.push(this);
  55536. this.id = this._scene.soundTracks.length - 1;
  55537. }
  55538. }
  55539. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55540. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55541. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55542. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55543. if (this._options) {
  55544. if (this._options.volume) {
  55545. this._outputAudioNode.gain.value = this._options.volume;
  55546. }
  55547. if (this._options.mainTrack) {
  55548. this._isMainTrack = this._options.mainTrack;
  55549. }
  55550. }
  55551. this._isInitialized = true;
  55552. }
  55553. };
  55554. SoundTrack.prototype.dispose = function () {
  55555. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55556. if (this._connectedAnalyser) {
  55557. this._connectedAnalyser.stopDebugCanvas();
  55558. }
  55559. while (this.soundCollection.length) {
  55560. this.soundCollection[0].dispose();
  55561. }
  55562. if (this._outputAudioNode) {
  55563. this._outputAudioNode.disconnect();
  55564. }
  55565. this._outputAudioNode = null;
  55566. }
  55567. };
  55568. SoundTrack.prototype.AddSound = function (sound) {
  55569. if (!this._isInitialized) {
  55570. this._initializeSoundTrackAudioGraph();
  55571. }
  55572. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55573. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55574. }
  55575. if (sound.soundTrackId) {
  55576. if (sound.soundTrackId === -1) {
  55577. this._scene.mainSoundTrack.RemoveSound(sound);
  55578. }
  55579. else {
  55580. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55581. }
  55582. }
  55583. this.soundCollection.push(sound);
  55584. sound.soundTrackId = this.id;
  55585. };
  55586. SoundTrack.prototype.RemoveSound = function (sound) {
  55587. var index = this.soundCollection.indexOf(sound);
  55588. if (index !== -1) {
  55589. this.soundCollection.splice(index, 1);
  55590. }
  55591. };
  55592. SoundTrack.prototype.setVolume = function (newVolume) {
  55593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55594. this._outputAudioNode.gain.value = newVolume;
  55595. }
  55596. };
  55597. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55598. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55599. for (var i = 0; i < this.soundCollection.length; i++) {
  55600. this.soundCollection[i].switchPanningModelToHRTF();
  55601. }
  55602. }
  55603. };
  55604. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55605. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55606. for (var i = 0; i < this.soundCollection.length; i++) {
  55607. this.soundCollection[i].switchPanningModelToEqualPower();
  55608. }
  55609. }
  55610. };
  55611. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55612. if (this._connectedAnalyser) {
  55613. this._connectedAnalyser.stopDebugCanvas();
  55614. }
  55615. this._connectedAnalyser = analyser;
  55616. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55617. this._outputAudioNode.disconnect();
  55618. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55619. }
  55620. };
  55621. return SoundTrack;
  55622. }());
  55623. BABYLON.SoundTrack = SoundTrack;
  55624. })(BABYLON || (BABYLON = {}));
  55625. //# sourceMappingURL=babylon.soundtrack.js.map
  55626. var BABYLON;
  55627. (function (BABYLON) {
  55628. var Analyser = /** @class */ (function () {
  55629. function Analyser(scene) {
  55630. this.SMOOTHING = 0.75;
  55631. this.FFT_SIZE = 512;
  55632. this.BARGRAPHAMPLITUDE = 256;
  55633. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55634. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55635. this._scene = scene;
  55636. this._audioEngine = BABYLON.Engine.audioEngine;
  55637. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55638. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55639. this._webAudioAnalyser.minDecibels = -140;
  55640. this._webAudioAnalyser.maxDecibels = 0;
  55641. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55642. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55643. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55644. }
  55645. }
  55646. Analyser.prototype.getFrequencyBinCount = function () {
  55647. if (this._audioEngine.canUseWebAudio) {
  55648. return this._webAudioAnalyser.frequencyBinCount;
  55649. }
  55650. else {
  55651. return 0;
  55652. }
  55653. };
  55654. Analyser.prototype.getByteFrequencyData = function () {
  55655. if (this._audioEngine.canUseWebAudio) {
  55656. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55657. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55658. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55659. }
  55660. return this._byteFreqs;
  55661. };
  55662. Analyser.prototype.getByteTimeDomainData = function () {
  55663. if (this._audioEngine.canUseWebAudio) {
  55664. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55665. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55666. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55667. }
  55668. return this._byteTime;
  55669. };
  55670. Analyser.prototype.getFloatFrequencyData = function () {
  55671. if (this._audioEngine.canUseWebAudio) {
  55672. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55673. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55674. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55675. }
  55676. return this._floatFreqs;
  55677. };
  55678. Analyser.prototype.drawDebugCanvas = function () {
  55679. var _this = this;
  55680. if (this._audioEngine.canUseWebAudio) {
  55681. if (!this._debugCanvas) {
  55682. this._debugCanvas = document.createElement("canvas");
  55683. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55684. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55685. this._debugCanvas.style.position = "absolute";
  55686. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55687. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55688. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55689. document.body.appendChild(this._debugCanvas);
  55690. this._registerFunc = function () {
  55691. _this.drawDebugCanvas();
  55692. };
  55693. this._scene.registerBeforeRender(this._registerFunc);
  55694. }
  55695. if (this._registerFunc && this._debugCanvasContext) {
  55696. var workingArray = this.getByteFrequencyData();
  55697. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55698. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55699. // Draw the frequency domain chart.
  55700. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55701. var value = workingArray[i];
  55702. var percent = value / this.BARGRAPHAMPLITUDE;
  55703. var height = this.DEBUGCANVASSIZE.height * percent;
  55704. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55705. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55706. var hue = i / this.getFrequencyBinCount() * 360;
  55707. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55708. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55709. }
  55710. }
  55711. }
  55712. };
  55713. Analyser.prototype.stopDebugCanvas = function () {
  55714. if (this._debugCanvas) {
  55715. if (this._registerFunc) {
  55716. this._scene.unregisterBeforeRender(this._registerFunc);
  55717. this._registerFunc = null;
  55718. }
  55719. document.body.removeChild(this._debugCanvas);
  55720. this._debugCanvas = null;
  55721. this._debugCanvasContext = null;
  55722. }
  55723. };
  55724. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55725. if (this._audioEngine.canUseWebAudio) {
  55726. inputAudioNode.connect(this._webAudioAnalyser);
  55727. this._webAudioAnalyser.connect(outputAudioNode);
  55728. }
  55729. };
  55730. Analyser.prototype.dispose = function () {
  55731. if (this._audioEngine.canUseWebAudio) {
  55732. this._webAudioAnalyser.disconnect();
  55733. }
  55734. };
  55735. return Analyser;
  55736. }());
  55737. BABYLON.Analyser = Analyser;
  55738. })(BABYLON || (BABYLON = {}));
  55739. //# sourceMappingURL=babylon.analyser.js.map
  55740. var BABYLON;
  55741. (function (BABYLON) {
  55742. var CubeTexture = /** @class */ (function (_super) {
  55743. __extends(CubeTexture, _super);
  55744. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55745. if (extensions === void 0) { extensions = null; }
  55746. if (noMipmap === void 0) { noMipmap = false; }
  55747. if (files === void 0) { files = null; }
  55748. if (onLoad === void 0) { onLoad = null; }
  55749. if (onError === void 0) { onError = null; }
  55750. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55751. if (prefiltered === void 0) { prefiltered = false; }
  55752. if (forcedExtension === void 0) { forcedExtension = null; }
  55753. var _this = _super.call(this, scene) || this;
  55754. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55755. /**
  55756. * Gets or sets the center of the bounding box associated with the cube texture
  55757. * It must define where the camera used to render the texture was set
  55758. */
  55759. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55760. _this.name = rootUrl;
  55761. _this.url = rootUrl;
  55762. _this._noMipmap = noMipmap;
  55763. _this.hasAlpha = false;
  55764. _this._format = format;
  55765. _this._prefiltered = prefiltered;
  55766. _this.isCube = true;
  55767. _this._textureMatrix = BABYLON.Matrix.Identity();
  55768. if (prefiltered) {
  55769. _this.gammaSpace = false;
  55770. }
  55771. if (!rootUrl && !files) {
  55772. return _this;
  55773. }
  55774. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55775. var lastDot = rootUrl.lastIndexOf(".");
  55776. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55777. var isDDS = (extension === ".dds");
  55778. if (!files) {
  55779. if (!isDDS && !extensions) {
  55780. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55781. }
  55782. files = [];
  55783. if (extensions) {
  55784. for (var index = 0; index < extensions.length; index++) {
  55785. files.push(rootUrl + extensions[index]);
  55786. }
  55787. }
  55788. }
  55789. _this._files = files;
  55790. if (!_this._texture) {
  55791. if (!scene.useDelayedTextureLoading) {
  55792. if (prefiltered) {
  55793. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55794. }
  55795. else {
  55796. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55797. }
  55798. }
  55799. else {
  55800. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55801. }
  55802. }
  55803. else if (onLoad) {
  55804. if (_this._texture.isReady) {
  55805. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55806. }
  55807. else {
  55808. _this._texture.onLoadedObservable.add(onLoad);
  55809. }
  55810. }
  55811. return _this;
  55812. }
  55813. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  55814. get: function () {
  55815. return this._boundingBoxSize;
  55816. },
  55817. /**
  55818. * Gets or sets the size of the bounding box associated with the cube texture
  55819. * When defined, the cubemap will switch to local mode
  55820. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  55821. * @example https://www.babylonjs-playground.com/#RNASML
  55822. */
  55823. set: function (value) {
  55824. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  55825. return;
  55826. }
  55827. this._boundingBoxSize = value;
  55828. var scene = this.getScene();
  55829. if (scene) {
  55830. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  55831. }
  55832. },
  55833. enumerable: true,
  55834. configurable: true
  55835. });
  55836. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55837. return new CubeTexture("", scene, null, noMipmap, files);
  55838. };
  55839. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55840. if (forcedExtension === void 0) { forcedExtension = null; }
  55841. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55842. };
  55843. // Methods
  55844. CubeTexture.prototype.delayLoad = function () {
  55845. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55846. return;
  55847. }
  55848. var scene = this.getScene();
  55849. if (!scene) {
  55850. return;
  55851. }
  55852. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55853. this._texture = this._getFromCache(this.url, this._noMipmap);
  55854. if (!this._texture) {
  55855. if (this._prefiltered) {
  55856. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55857. }
  55858. else {
  55859. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55860. }
  55861. }
  55862. };
  55863. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55864. return this._textureMatrix;
  55865. };
  55866. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55867. this._textureMatrix = value;
  55868. };
  55869. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55870. var texture = BABYLON.SerializationHelper.Parse(function () {
  55871. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55872. }, parsedTexture, scene);
  55873. // Animations
  55874. if (parsedTexture.animations) {
  55875. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  55876. var parsedAnimation = parsedTexture.animations[animationIndex];
  55877. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55878. }
  55879. }
  55880. return texture;
  55881. };
  55882. CubeTexture.prototype.clone = function () {
  55883. var _this = this;
  55884. return BABYLON.SerializationHelper.Clone(function () {
  55885. var scene = _this.getScene();
  55886. if (!scene) {
  55887. return _this;
  55888. }
  55889. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  55890. }, this);
  55891. };
  55892. return CubeTexture;
  55893. }(BABYLON.BaseTexture));
  55894. BABYLON.CubeTexture = CubeTexture;
  55895. })(BABYLON || (BABYLON = {}));
  55896. //# sourceMappingURL=babylon.cubeTexture.js.map
  55897. var BABYLON;
  55898. (function (BABYLON) {
  55899. var RenderTargetTexture = /** @class */ (function (_super) {
  55900. __extends(RenderTargetTexture, _super);
  55901. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  55902. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  55903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55904. if (isCube === void 0) { isCube = false; }
  55905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55906. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55907. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  55908. if (isMulti === void 0) { isMulti = false; }
  55909. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55910. _this.isCube = isCube;
  55911. /**
  55912. * Use this list to define the list of mesh you want to render.
  55913. */
  55914. _this.renderList = new Array();
  55915. _this.renderParticles = true;
  55916. _this.renderSprites = false;
  55917. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  55918. _this.ignoreCameraViewport = false;
  55919. // Events
  55920. /**
  55921. * An event triggered when the texture is unbind.
  55922. * @type {BABYLON.Observable}
  55923. */
  55924. _this.onBeforeBindObservable = new BABYLON.Observable();
  55925. /**
  55926. * An event triggered when the texture is unbind.
  55927. * @type {BABYLON.Observable}
  55928. */
  55929. _this.onAfterUnbindObservable = new BABYLON.Observable();
  55930. /**
  55931. * An event triggered before rendering the texture
  55932. * @type {BABYLON.Observable}
  55933. */
  55934. _this.onBeforeRenderObservable = new BABYLON.Observable();
  55935. /**
  55936. * An event triggered after rendering the texture
  55937. * @type {BABYLON.Observable}
  55938. */
  55939. _this.onAfterRenderObservable = new BABYLON.Observable();
  55940. /**
  55941. * An event triggered after the texture clear
  55942. * @type {BABYLON.Observable}
  55943. */
  55944. _this.onClearObservable = new BABYLON.Observable();
  55945. _this._currentRefreshId = -1;
  55946. _this._refreshRate = 1;
  55947. _this._samples = 1;
  55948. /**
  55949. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  55950. * It must define where the camera used to render the texture is set
  55951. */
  55952. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55953. scene = _this.getScene();
  55954. if (!scene) {
  55955. return _this;
  55956. }
  55957. _this._engine = scene.getEngine();
  55958. _this.name = name;
  55959. _this.isRenderTarget = true;
  55960. _this._initialSizeParameter = size;
  55961. _this._processSizeParameter(size);
  55962. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  55963. });
  55964. _this._generateMipMaps = generateMipMaps ? true : false;
  55965. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  55966. // Rendering groups
  55967. _this._renderingManager = new BABYLON.RenderingManager(scene);
  55968. if (isMulti) {
  55969. return _this;
  55970. }
  55971. _this._renderTargetOptions = {
  55972. generateMipMaps: generateMipMaps,
  55973. type: type,
  55974. samplingMode: samplingMode,
  55975. generateDepthBuffer: generateDepthBuffer,
  55976. generateStencilBuffer: generateStencilBuffer
  55977. };
  55978. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  55979. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55980. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55981. }
  55982. if (isCube) {
  55983. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  55984. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  55985. _this._textureMatrix = BABYLON.Matrix.Identity();
  55986. }
  55987. else {
  55988. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  55989. }
  55990. return _this;
  55991. }
  55992. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  55993. get: function () {
  55994. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  55995. },
  55996. enumerable: true,
  55997. configurable: true
  55998. });
  55999. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56000. get: function () {
  56001. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56002. },
  56003. enumerable: true,
  56004. configurable: true
  56005. });
  56006. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56007. get: function () {
  56008. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56009. },
  56010. enumerable: true,
  56011. configurable: true
  56012. });
  56013. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56014. set: function (callback) {
  56015. if (this._onAfterUnbindObserver) {
  56016. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56017. }
  56018. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56019. },
  56020. enumerable: true,
  56021. configurable: true
  56022. });
  56023. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56024. set: function (callback) {
  56025. if (this._onBeforeRenderObserver) {
  56026. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56027. }
  56028. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56029. },
  56030. enumerable: true,
  56031. configurable: true
  56032. });
  56033. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56034. set: function (callback) {
  56035. if (this._onAfterRenderObserver) {
  56036. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56037. }
  56038. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56039. },
  56040. enumerable: true,
  56041. configurable: true
  56042. });
  56043. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56044. set: function (callback) {
  56045. if (this._onClearObserver) {
  56046. this.onClearObservable.remove(this._onClearObserver);
  56047. }
  56048. this._onClearObserver = this.onClearObservable.add(callback);
  56049. },
  56050. enumerable: true,
  56051. configurable: true
  56052. });
  56053. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56054. get: function () {
  56055. return this._renderTargetOptions;
  56056. },
  56057. enumerable: true,
  56058. configurable: true
  56059. });
  56060. RenderTargetTexture.prototype._onRatioRescale = function () {
  56061. if (this._sizeRatio) {
  56062. this.resize(this._initialSizeParameter);
  56063. }
  56064. };
  56065. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56066. get: function () {
  56067. return this._boundingBoxSize;
  56068. },
  56069. /**
  56070. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56071. * When defined, the cubemap will switch to local mode
  56072. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56073. * @example https://www.babylonjs-playground.com/#RNASML
  56074. */
  56075. set: function (value) {
  56076. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56077. return;
  56078. }
  56079. this._boundingBoxSize = value;
  56080. var scene = this.getScene();
  56081. if (scene) {
  56082. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56083. }
  56084. },
  56085. enumerable: true,
  56086. configurable: true
  56087. });
  56088. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56089. if (size.ratio) {
  56090. this._sizeRatio = size.ratio;
  56091. this._size = {
  56092. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56093. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56094. };
  56095. }
  56096. else {
  56097. this._size = size;
  56098. }
  56099. };
  56100. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56101. get: function () {
  56102. return this._samples;
  56103. },
  56104. set: function (value) {
  56105. if (this._samples === value) {
  56106. return;
  56107. }
  56108. var scene = this.getScene();
  56109. if (!scene) {
  56110. return;
  56111. }
  56112. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56113. },
  56114. enumerable: true,
  56115. configurable: true
  56116. });
  56117. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56118. this._currentRefreshId = -1;
  56119. };
  56120. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56121. get: function () {
  56122. return this._refreshRate;
  56123. },
  56124. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56125. set: function (value) {
  56126. this._refreshRate = value;
  56127. this.resetRefreshCounter();
  56128. },
  56129. enumerable: true,
  56130. configurable: true
  56131. });
  56132. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56133. if (!this._postProcessManager) {
  56134. var scene = this.getScene();
  56135. if (!scene) {
  56136. return;
  56137. }
  56138. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56139. this._postProcesses = new Array();
  56140. }
  56141. this._postProcesses.push(postProcess);
  56142. this._postProcesses[0].autoClear = false;
  56143. };
  56144. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56145. if (!this._postProcesses) {
  56146. return;
  56147. }
  56148. if (dispose) {
  56149. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56150. var postProcess = _a[_i];
  56151. postProcess.dispose();
  56152. }
  56153. }
  56154. this._postProcesses = [];
  56155. };
  56156. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56157. if (!this._postProcesses) {
  56158. return;
  56159. }
  56160. var index = this._postProcesses.indexOf(postProcess);
  56161. if (index === -1) {
  56162. return;
  56163. }
  56164. this._postProcesses.splice(index, 1);
  56165. if (this._postProcesses.length > 0) {
  56166. this._postProcesses[0].autoClear = false;
  56167. }
  56168. };
  56169. RenderTargetTexture.prototype._shouldRender = function () {
  56170. if (this._currentRefreshId === -1) {
  56171. this._currentRefreshId = 1;
  56172. return true;
  56173. }
  56174. if (this.refreshRate === this._currentRefreshId) {
  56175. this._currentRefreshId = 1;
  56176. return true;
  56177. }
  56178. this._currentRefreshId++;
  56179. return false;
  56180. };
  56181. RenderTargetTexture.prototype.getRenderSize = function () {
  56182. if (this._size.width) {
  56183. return this._size.width;
  56184. }
  56185. return this._size;
  56186. };
  56187. RenderTargetTexture.prototype.getRenderWidth = function () {
  56188. if (this._size.width) {
  56189. return this._size.width;
  56190. }
  56191. return this._size;
  56192. };
  56193. RenderTargetTexture.prototype.getRenderHeight = function () {
  56194. if (this._size.width) {
  56195. return this._size.height;
  56196. }
  56197. return this._size;
  56198. };
  56199. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56200. get: function () {
  56201. return true;
  56202. },
  56203. enumerable: true,
  56204. configurable: true
  56205. });
  56206. RenderTargetTexture.prototype.scale = function (ratio) {
  56207. var newSize = this.getRenderSize() * ratio;
  56208. this.resize(newSize);
  56209. };
  56210. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56211. if (this.isCube) {
  56212. return this._textureMatrix;
  56213. }
  56214. return _super.prototype.getReflectionTextureMatrix.call(this);
  56215. };
  56216. RenderTargetTexture.prototype.resize = function (size) {
  56217. this.releaseInternalTexture();
  56218. var scene = this.getScene();
  56219. if (!scene) {
  56220. return;
  56221. }
  56222. this._processSizeParameter(size);
  56223. if (this.isCube) {
  56224. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56225. }
  56226. else {
  56227. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56228. }
  56229. };
  56230. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56231. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56232. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56233. var scene = this.getScene();
  56234. if (!scene) {
  56235. return;
  56236. }
  56237. var engine = scene.getEngine();
  56238. if (this.useCameraPostProcesses !== undefined) {
  56239. useCameraPostProcess = this.useCameraPostProcesses;
  56240. }
  56241. if (this._waitingRenderList) {
  56242. this.renderList = [];
  56243. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56244. var id = this._waitingRenderList[index];
  56245. var mesh_1 = scene.getMeshByID(id);
  56246. if (mesh_1) {
  56247. this.renderList.push(mesh_1);
  56248. }
  56249. }
  56250. delete this._waitingRenderList;
  56251. }
  56252. // Is predicate defined?
  56253. if (this.renderListPredicate) {
  56254. if (this.renderList) {
  56255. this.renderList.splice(0); // Clear previous renderList
  56256. }
  56257. else {
  56258. this.renderList = [];
  56259. }
  56260. var scene = this.getScene();
  56261. if (!scene) {
  56262. return;
  56263. }
  56264. var sceneMeshes = scene.meshes;
  56265. for (var index = 0; index < sceneMeshes.length; index++) {
  56266. var mesh = sceneMeshes[index];
  56267. if (this.renderListPredicate(mesh)) {
  56268. this.renderList.push(mesh);
  56269. }
  56270. }
  56271. }
  56272. this.onBeforeBindObservable.notifyObservers(this);
  56273. // Set custom projection.
  56274. // Needs to be before binding to prevent changing the aspect ratio.
  56275. var camera;
  56276. if (this.activeCamera) {
  56277. camera = this.activeCamera;
  56278. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56279. if (this.activeCamera !== scene.activeCamera) {
  56280. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56281. }
  56282. }
  56283. else {
  56284. camera = scene.activeCamera;
  56285. if (camera) {
  56286. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56287. }
  56288. }
  56289. // Prepare renderingManager
  56290. this._renderingManager.reset();
  56291. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56292. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56293. var sceneRenderId = scene.getRenderId();
  56294. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56295. var mesh = currentRenderList[meshIndex];
  56296. if (mesh) {
  56297. if (!mesh.isReady()) {
  56298. // Reset _currentRefreshId
  56299. this.resetRefreshCounter();
  56300. continue;
  56301. }
  56302. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56303. var isMasked = void 0;
  56304. if (!this.renderList && camera) {
  56305. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56306. }
  56307. else {
  56308. isMasked = false;
  56309. }
  56310. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56311. mesh._activate(sceneRenderId);
  56312. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56313. var subMesh = mesh.subMeshes[subIndex];
  56314. scene._activeIndices.addCount(subMesh.indexCount, false);
  56315. this._renderingManager.dispatch(subMesh, mesh);
  56316. }
  56317. }
  56318. }
  56319. }
  56320. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56321. var particleSystem = scene.particleSystems[particleIndex];
  56322. var emitter = particleSystem.emitter;
  56323. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56324. continue;
  56325. }
  56326. if (currentRenderList.indexOf(emitter) >= 0) {
  56327. this._renderingManager.dispatchParticles(particleSystem);
  56328. }
  56329. }
  56330. if (this.isCube) {
  56331. for (var face = 0; face < 6; face++) {
  56332. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56333. scene.incrementRenderId();
  56334. scene.resetCachedMaterial();
  56335. }
  56336. }
  56337. else {
  56338. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56339. }
  56340. this.onAfterUnbindObservable.notifyObservers(this);
  56341. if (scene.activeCamera) {
  56342. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56343. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56344. }
  56345. engine.setViewport(scene.activeCamera.viewport);
  56346. }
  56347. scene.resetCachedMaterial();
  56348. };
  56349. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56350. var minimum = 128;
  56351. var x = renderDimension * scale;
  56352. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56353. // Ensure we don't exceed the render dimension (while staying POT)
  56354. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56355. };
  56356. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56357. var _this = this;
  56358. if (!this._texture) {
  56359. return;
  56360. }
  56361. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56362. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56363. });
  56364. };
  56365. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56366. var scene = this.getScene();
  56367. if (!scene) {
  56368. return;
  56369. }
  56370. var engine = scene.getEngine();
  56371. if (!this._texture) {
  56372. return;
  56373. }
  56374. // Bind
  56375. if (this._postProcessManager) {
  56376. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56377. }
  56378. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56379. if (this._texture) {
  56380. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56381. }
  56382. }
  56383. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56384. // Clear
  56385. if (this.onClearObservable.hasObservers()) {
  56386. this.onClearObservable.notifyObservers(engine);
  56387. }
  56388. else {
  56389. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56390. }
  56391. if (!this._doNotChangeAspectRatio) {
  56392. scene.updateTransformMatrix(true);
  56393. }
  56394. // Render
  56395. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56396. if (this._postProcessManager) {
  56397. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56398. }
  56399. else if (useCameraPostProcess) {
  56400. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56401. }
  56402. if (!this._doNotChangeAspectRatio) {
  56403. scene.updateTransformMatrix(true);
  56404. }
  56405. // Dump ?
  56406. if (dumpForDebug) {
  56407. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56408. }
  56409. // Unbind
  56410. if (!this.isCube || faceIndex === 5) {
  56411. if (this.isCube) {
  56412. if (faceIndex === 5) {
  56413. engine.generateMipMapsForCubemap(this._texture);
  56414. }
  56415. }
  56416. this.unbindFrameBuffer(engine, faceIndex);
  56417. }
  56418. else {
  56419. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56420. }
  56421. };
  56422. /**
  56423. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56424. * This allowed control for front to back rendering or reversly depending of the special needs.
  56425. *
  56426. * @param renderingGroupId The rendering group id corresponding to its index
  56427. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56428. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56429. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56430. */
  56431. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56432. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56433. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56434. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56435. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56436. };
  56437. /**
  56438. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56439. *
  56440. * @param renderingGroupId The rendering group id corresponding to its index
  56441. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56442. */
  56443. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56444. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56445. };
  56446. RenderTargetTexture.prototype.clone = function () {
  56447. var textureSize = this.getSize();
  56448. 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);
  56449. // Base texture
  56450. newTexture.hasAlpha = this.hasAlpha;
  56451. newTexture.level = this.level;
  56452. // RenderTarget Texture
  56453. newTexture.coordinatesMode = this.coordinatesMode;
  56454. if (this.renderList) {
  56455. newTexture.renderList = this.renderList.slice(0);
  56456. }
  56457. return newTexture;
  56458. };
  56459. RenderTargetTexture.prototype.serialize = function () {
  56460. if (!this.name) {
  56461. return null;
  56462. }
  56463. var serializationObject = _super.prototype.serialize.call(this);
  56464. serializationObject.renderTargetSize = this.getRenderSize();
  56465. serializationObject.renderList = [];
  56466. if (this.renderList) {
  56467. for (var index = 0; index < this.renderList.length; index++) {
  56468. serializationObject.renderList.push(this.renderList[index].id);
  56469. }
  56470. }
  56471. return serializationObject;
  56472. };
  56473. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56474. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56475. var objBuffer = this.getInternalTexture();
  56476. var scene = this.getScene();
  56477. if (objBuffer && scene) {
  56478. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56479. }
  56480. };
  56481. RenderTargetTexture.prototype.dispose = function () {
  56482. if (this._postProcessManager) {
  56483. this._postProcessManager.dispose();
  56484. this._postProcessManager = null;
  56485. }
  56486. this.clearPostProcesses(true);
  56487. if (this._resizeObserver) {
  56488. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56489. this._resizeObserver = null;
  56490. }
  56491. this.renderList = null;
  56492. // Remove from custom render targets
  56493. var scene = this.getScene();
  56494. if (!scene) {
  56495. return;
  56496. }
  56497. var index = scene.customRenderTargets.indexOf(this);
  56498. if (index >= 0) {
  56499. scene.customRenderTargets.splice(index, 1);
  56500. }
  56501. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56502. var camera = _a[_i];
  56503. index = camera.customRenderTargets.indexOf(this);
  56504. if (index >= 0) {
  56505. camera.customRenderTargets.splice(index, 1);
  56506. }
  56507. }
  56508. _super.prototype.dispose.call(this);
  56509. };
  56510. RenderTargetTexture.prototype._rebuild = function () {
  56511. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56512. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56513. }
  56514. if (this._postProcessManager) {
  56515. this._postProcessManager._rebuild();
  56516. }
  56517. };
  56518. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56519. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56520. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56521. return RenderTargetTexture;
  56522. }(BABYLON.Texture));
  56523. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56524. })(BABYLON || (BABYLON = {}));
  56525. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56526. var BABYLON;
  56527. (function (BABYLON) {
  56528. ;
  56529. var MultiRenderTarget = /** @class */ (function (_super) {
  56530. __extends(MultiRenderTarget, _super);
  56531. function MultiRenderTarget(name, size, count, scene, options) {
  56532. var _this = this;
  56533. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56534. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56535. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56536. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56537. _this._engine = scene.getEngine();
  56538. if (!_this.isSupported) {
  56539. _this.dispose();
  56540. return;
  56541. }
  56542. var types = [];
  56543. var samplingModes = [];
  56544. for (var i = 0; i < count; i++) {
  56545. if (options && options.types && options.types[i] !== undefined) {
  56546. types.push(options.types[i]);
  56547. }
  56548. else {
  56549. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56550. }
  56551. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56552. samplingModes.push(options.samplingModes[i]);
  56553. }
  56554. else {
  56555. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56556. }
  56557. }
  56558. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56559. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56560. _this._size = size;
  56561. _this._multiRenderTargetOptions = {
  56562. samplingModes: samplingModes,
  56563. generateMipMaps: generateMipMaps,
  56564. generateDepthBuffer: generateDepthBuffer,
  56565. generateStencilBuffer: generateStencilBuffer,
  56566. generateDepthTexture: generateDepthTexture,
  56567. types: types,
  56568. textureCount: count
  56569. };
  56570. _this._createInternalTextures();
  56571. _this._createTextures();
  56572. return _this;
  56573. }
  56574. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56575. get: function () {
  56576. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56577. },
  56578. enumerable: true,
  56579. configurable: true
  56580. });
  56581. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56582. get: function () {
  56583. return this._textures;
  56584. },
  56585. enumerable: true,
  56586. configurable: true
  56587. });
  56588. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56589. get: function () {
  56590. return this._textures[this._textures.length - 1];
  56591. },
  56592. enumerable: true,
  56593. configurable: true
  56594. });
  56595. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56596. set: function (wrap) {
  56597. if (this._textures) {
  56598. for (var i = 0; i < this._textures.length; i++) {
  56599. this._textures[i].wrapU = wrap;
  56600. }
  56601. }
  56602. },
  56603. enumerable: true,
  56604. configurable: true
  56605. });
  56606. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56607. set: function (wrap) {
  56608. if (this._textures) {
  56609. for (var i = 0; i < this._textures.length; i++) {
  56610. this._textures[i].wrapV = wrap;
  56611. }
  56612. }
  56613. },
  56614. enumerable: true,
  56615. configurable: true
  56616. });
  56617. MultiRenderTarget.prototype._rebuild = function () {
  56618. this.releaseInternalTextures();
  56619. this._createInternalTextures();
  56620. for (var i = 0; i < this._internalTextures.length; i++) {
  56621. var texture = this._textures[i];
  56622. texture._texture = this._internalTextures[i];
  56623. }
  56624. // Keeps references to frame buffer and stencil/depth buffer
  56625. this._texture = this._internalTextures[0];
  56626. };
  56627. MultiRenderTarget.prototype._createInternalTextures = function () {
  56628. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56629. };
  56630. MultiRenderTarget.prototype._createTextures = function () {
  56631. this._textures = [];
  56632. for (var i = 0; i < this._internalTextures.length; i++) {
  56633. var texture = new BABYLON.Texture(null, this.getScene());
  56634. texture._texture = this._internalTextures[i];
  56635. this._textures.push(texture);
  56636. }
  56637. // Keeps references to frame buffer and stencil/depth buffer
  56638. this._texture = this._internalTextures[0];
  56639. };
  56640. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56641. get: function () {
  56642. return this._samples;
  56643. },
  56644. set: function (value) {
  56645. if (this._samples === value) {
  56646. return;
  56647. }
  56648. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56649. },
  56650. enumerable: true,
  56651. configurable: true
  56652. });
  56653. MultiRenderTarget.prototype.resize = function (size) {
  56654. this.releaseInternalTextures();
  56655. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56656. this._createInternalTextures();
  56657. };
  56658. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56659. var _this = this;
  56660. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56661. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56662. });
  56663. };
  56664. MultiRenderTarget.prototype.dispose = function () {
  56665. this.releaseInternalTextures();
  56666. _super.prototype.dispose.call(this);
  56667. };
  56668. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56669. if (!this._internalTextures) {
  56670. return;
  56671. }
  56672. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56673. if (this._internalTextures[i] !== undefined) {
  56674. this._internalTextures[i].dispose();
  56675. this._internalTextures.splice(i, 1);
  56676. }
  56677. }
  56678. };
  56679. return MultiRenderTarget;
  56680. }(BABYLON.RenderTargetTexture));
  56681. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56682. })(BABYLON || (BABYLON = {}));
  56683. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56684. var BABYLON;
  56685. (function (BABYLON) {
  56686. var MirrorTexture = /** @class */ (function (_super) {
  56687. __extends(MirrorTexture, _super);
  56688. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56689. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56690. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56691. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56692. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56693. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56694. _this._transformMatrix = BABYLON.Matrix.Zero();
  56695. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56696. _this._adaptiveBlurKernel = 0;
  56697. _this._blurKernelX = 0;
  56698. _this._blurKernelY = 0;
  56699. _this._blurRatio = 1.0;
  56700. _this.ignoreCameraViewport = true;
  56701. _this.onBeforeRenderObservable.add(function () {
  56702. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56703. _this._savedViewMatrix = scene.getViewMatrix();
  56704. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56705. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56706. scene.clipPlane = _this.mirrorPlane;
  56707. scene.getEngine().cullBackFaces = false;
  56708. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56709. });
  56710. _this.onAfterRenderObservable.add(function () {
  56711. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56712. scene.getEngine().cullBackFaces = true;
  56713. scene._mirroredCameraPosition = null;
  56714. delete scene.clipPlane;
  56715. });
  56716. return _this;
  56717. }
  56718. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56719. get: function () {
  56720. return this._blurRatio;
  56721. },
  56722. set: function (value) {
  56723. if (this._blurRatio === value) {
  56724. return;
  56725. }
  56726. this._blurRatio = value;
  56727. this._preparePostProcesses();
  56728. },
  56729. enumerable: true,
  56730. configurable: true
  56731. });
  56732. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56733. set: function (value) {
  56734. this._adaptiveBlurKernel = value;
  56735. this._autoComputeBlurKernel();
  56736. },
  56737. enumerable: true,
  56738. configurable: true
  56739. });
  56740. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56741. set: function (value) {
  56742. this.blurKernelX = value;
  56743. this.blurKernelY = value;
  56744. },
  56745. enumerable: true,
  56746. configurable: true
  56747. });
  56748. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56749. get: function () {
  56750. return this._blurKernelX;
  56751. },
  56752. set: function (value) {
  56753. if (this._blurKernelX === value) {
  56754. return;
  56755. }
  56756. this._blurKernelX = value;
  56757. this._preparePostProcesses();
  56758. },
  56759. enumerable: true,
  56760. configurable: true
  56761. });
  56762. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56763. get: function () {
  56764. return this._blurKernelY;
  56765. },
  56766. set: function (value) {
  56767. if (this._blurKernelY === value) {
  56768. return;
  56769. }
  56770. this._blurKernelY = value;
  56771. this._preparePostProcesses();
  56772. },
  56773. enumerable: true,
  56774. configurable: true
  56775. });
  56776. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56777. var engine = this.getScene().getEngine();
  56778. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56779. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56780. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56781. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56782. };
  56783. MirrorTexture.prototype._onRatioRescale = function () {
  56784. if (this._sizeRatio) {
  56785. this.resize(this._initialSizeParameter);
  56786. if (!this._adaptiveBlurKernel) {
  56787. this._preparePostProcesses();
  56788. }
  56789. }
  56790. if (this._adaptiveBlurKernel) {
  56791. this._autoComputeBlurKernel();
  56792. }
  56793. };
  56794. MirrorTexture.prototype._preparePostProcesses = function () {
  56795. this.clearPostProcesses(true);
  56796. if (this._blurKernelX && this._blurKernelY) {
  56797. var engine = this.getScene().getEngine();
  56798. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56799. 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);
  56800. this._blurX.autoClear = false;
  56801. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56802. this._blurX.inputTexture = this._texture;
  56803. }
  56804. else {
  56805. this._blurX.alwaysForcePOT = true;
  56806. }
  56807. 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);
  56808. this._blurY.autoClear = false;
  56809. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56810. this.addPostProcess(this._blurX);
  56811. this.addPostProcess(this._blurY);
  56812. }
  56813. else {
  56814. if (this._blurY) {
  56815. this.removePostProcess(this._blurY);
  56816. this._blurY.dispose();
  56817. this._blurY = null;
  56818. }
  56819. if (this._blurX) {
  56820. this.removePostProcess(this._blurX);
  56821. this._blurX.dispose();
  56822. this._blurX = null;
  56823. }
  56824. }
  56825. };
  56826. MirrorTexture.prototype.clone = function () {
  56827. var scene = this.getScene();
  56828. if (!scene) {
  56829. return this;
  56830. }
  56831. var textureSize = this.getSize();
  56832. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56833. // Base texture
  56834. newTexture.hasAlpha = this.hasAlpha;
  56835. newTexture.level = this.level;
  56836. // Mirror Texture
  56837. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56838. if (this.renderList) {
  56839. newTexture.renderList = this.renderList.slice(0);
  56840. }
  56841. return newTexture;
  56842. };
  56843. MirrorTexture.prototype.serialize = function () {
  56844. if (!this.name) {
  56845. return null;
  56846. }
  56847. var serializationObject = _super.prototype.serialize.call(this);
  56848. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56849. return serializationObject;
  56850. };
  56851. return MirrorTexture;
  56852. }(BABYLON.RenderTargetTexture));
  56853. BABYLON.MirrorTexture = MirrorTexture;
  56854. })(BABYLON || (BABYLON = {}));
  56855. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56856. var BABYLON;
  56857. (function (BABYLON) {
  56858. /**
  56859. * Creates a refraction texture used by refraction channel of the standard material.
  56860. * @param name the texture name
  56861. * @param size size of the underlying texture
  56862. * @param scene root scene
  56863. */
  56864. var RefractionTexture = /** @class */ (function (_super) {
  56865. __extends(RefractionTexture, _super);
  56866. function RefractionTexture(name, size, scene, generateMipMaps) {
  56867. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56868. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56869. _this.depth = 2.0;
  56870. _this.onBeforeRenderObservable.add(function () {
  56871. scene.clipPlane = _this.refractionPlane;
  56872. });
  56873. _this.onAfterRenderObservable.add(function () {
  56874. delete scene.clipPlane;
  56875. });
  56876. return _this;
  56877. }
  56878. RefractionTexture.prototype.clone = function () {
  56879. var scene = this.getScene();
  56880. if (!scene) {
  56881. return this;
  56882. }
  56883. var textureSize = this.getSize();
  56884. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  56885. // Base texture
  56886. newTexture.hasAlpha = this.hasAlpha;
  56887. newTexture.level = this.level;
  56888. // Refraction Texture
  56889. newTexture.refractionPlane = this.refractionPlane.clone();
  56890. if (this.renderList) {
  56891. newTexture.renderList = this.renderList.slice(0);
  56892. }
  56893. newTexture.depth = this.depth;
  56894. return newTexture;
  56895. };
  56896. RefractionTexture.prototype.serialize = function () {
  56897. if (!this.name) {
  56898. return null;
  56899. }
  56900. var serializationObject = _super.prototype.serialize.call(this);
  56901. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  56902. serializationObject.depth = this.depth;
  56903. return serializationObject;
  56904. };
  56905. return RefractionTexture;
  56906. }(BABYLON.RenderTargetTexture));
  56907. BABYLON.RefractionTexture = RefractionTexture;
  56908. })(BABYLON || (BABYLON = {}));
  56909. //# sourceMappingURL=babylon.refractionTexture.js.map
  56910. var BABYLON;
  56911. (function (BABYLON) {
  56912. var DynamicTexture = /** @class */ (function (_super) {
  56913. __extends(DynamicTexture, _super);
  56914. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  56915. if (scene === void 0) { scene = null; }
  56916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56917. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56918. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  56919. _this.name = name;
  56920. _this._engine = _this.getScene().getEngine();
  56921. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56922. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56923. _this._generateMipMaps = generateMipMaps;
  56924. if (options.getContext) {
  56925. _this._canvas = options;
  56926. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56927. }
  56928. else {
  56929. _this._canvas = document.createElement("canvas");
  56930. if (options.width) {
  56931. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56932. }
  56933. else {
  56934. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  56935. }
  56936. }
  56937. var textureSize = _this.getSize();
  56938. _this._canvas.width = textureSize.width;
  56939. _this._canvas.height = textureSize.height;
  56940. _this._context = _this._canvas.getContext("2d");
  56941. return _this;
  56942. }
  56943. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  56944. get: function () {
  56945. return true;
  56946. },
  56947. enumerable: true,
  56948. configurable: true
  56949. });
  56950. DynamicTexture.prototype._recreate = function (textureSize) {
  56951. this._canvas.width = textureSize.width;
  56952. this._canvas.height = textureSize.height;
  56953. this.releaseInternalTexture();
  56954. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  56955. };
  56956. DynamicTexture.prototype.scale = function (ratio) {
  56957. var textureSize = this.getSize();
  56958. textureSize.width *= ratio;
  56959. textureSize.height *= ratio;
  56960. this._recreate(textureSize);
  56961. };
  56962. DynamicTexture.prototype.scaleTo = function (width, height) {
  56963. var textureSize = this.getSize();
  56964. textureSize.width = width;
  56965. textureSize.height = height;
  56966. this._recreate(textureSize);
  56967. };
  56968. DynamicTexture.prototype.getContext = function () {
  56969. return this._context;
  56970. };
  56971. DynamicTexture.prototype.clear = function () {
  56972. var size = this.getSize();
  56973. this._context.fillRect(0, 0, size.width, size.height);
  56974. };
  56975. DynamicTexture.prototype.update = function (invertY) {
  56976. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  56977. };
  56978. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  56979. if (update === void 0) { update = true; }
  56980. var size = this.getSize();
  56981. if (clearColor) {
  56982. this._context.fillStyle = clearColor;
  56983. this._context.fillRect(0, 0, size.width, size.height);
  56984. }
  56985. this._context.font = font;
  56986. if (x === null || x === undefined) {
  56987. var textSize = this._context.measureText(text);
  56988. x = (size.width - textSize.width) / 2;
  56989. }
  56990. if (y === null || y === undefined) {
  56991. var fontSize = parseInt((font.replace(/\D/g, '')));
  56992. ;
  56993. y = (size.height / 2) + (fontSize / 3.65);
  56994. }
  56995. this._context.fillStyle = color;
  56996. this._context.fillText(text, x, y);
  56997. if (update) {
  56998. this.update(invertY);
  56999. }
  57000. };
  57001. DynamicTexture.prototype.clone = function () {
  57002. var scene = this.getScene();
  57003. if (!scene) {
  57004. return this;
  57005. }
  57006. var textureSize = this.getSize();
  57007. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57008. // Base texture
  57009. newTexture.hasAlpha = this.hasAlpha;
  57010. newTexture.level = this.level;
  57011. // Dynamic Texture
  57012. newTexture.wrapU = this.wrapU;
  57013. newTexture.wrapV = this.wrapV;
  57014. return newTexture;
  57015. };
  57016. DynamicTexture.prototype._rebuild = function () {
  57017. this.update();
  57018. };
  57019. return DynamicTexture;
  57020. }(BABYLON.Texture));
  57021. BABYLON.DynamicTexture = DynamicTexture;
  57022. })(BABYLON || (BABYLON = {}));
  57023. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57024. var BABYLON;
  57025. (function (BABYLON) {
  57026. var VideoTexture = /** @class */ (function (_super) {
  57027. __extends(VideoTexture, _super);
  57028. /**
  57029. * Creates a video texture.
  57030. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57031. * @param {string | null} name optional name, will detect from video source, if not defined
  57032. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57033. * @param {BABYLON.Scene} scene is obviously the current scene.
  57034. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57035. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57036. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57037. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57038. */
  57039. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57040. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57041. if (invertY === void 0) { invertY = false; }
  57042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57043. if (settings === void 0) { settings = {
  57044. autoPlay: true,
  57045. loop: true,
  57046. autoUpdateTexture: true,
  57047. }; }
  57048. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57049. _this._createInternalTexture = function () {
  57050. if (_this._texture != null) {
  57051. return;
  57052. }
  57053. if (!_this._engine.needPOTTextures ||
  57054. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57055. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57056. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57057. }
  57058. else {
  57059. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57060. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57061. _this._generateMipMaps = false;
  57062. }
  57063. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57064. _this._texture.isReady = true;
  57065. _this._updateInternalTexture();
  57066. };
  57067. _this.reset = function () {
  57068. if (_this._texture == null) {
  57069. return;
  57070. }
  57071. _this._texture.dispose();
  57072. _this._texture = null;
  57073. };
  57074. _this._updateInternalTexture = function (e) {
  57075. if (_this._texture == null || !_this._texture.isReady) {
  57076. return;
  57077. }
  57078. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57079. return;
  57080. }
  57081. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57082. };
  57083. _this._engine = _this.getScene().getEngine();
  57084. _this._generateMipMaps = generateMipMaps;
  57085. _this._samplingMode = samplingMode;
  57086. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57087. _this.name = name || _this._getName(src);
  57088. _this.video = _this._getVideo(src);
  57089. if (settings.autoPlay !== undefined) {
  57090. _this.video.autoplay = settings.autoPlay;
  57091. }
  57092. if (settings.loop !== undefined) {
  57093. _this.video.loop = settings.loop;
  57094. }
  57095. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57096. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57097. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57098. _this.video.addEventListener("emptied", _this.reset);
  57099. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57100. _this._createInternalTexture();
  57101. }
  57102. return _this;
  57103. }
  57104. VideoTexture.prototype._getName = function (src) {
  57105. if (src instanceof HTMLVideoElement) {
  57106. return src.currentSrc;
  57107. }
  57108. if (typeof src === "object") {
  57109. return src.toString();
  57110. }
  57111. return src;
  57112. };
  57113. ;
  57114. VideoTexture.prototype._getVideo = function (src) {
  57115. if (src instanceof HTMLVideoElement) {
  57116. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57117. return src;
  57118. }
  57119. var video = document.createElement("video");
  57120. if (typeof src === "string") {
  57121. BABYLON.Tools.SetCorsBehavior(src, video);
  57122. video.src = src;
  57123. }
  57124. else {
  57125. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57126. src.forEach(function (url) {
  57127. var source = document.createElement("source");
  57128. source.src = url;
  57129. video.appendChild(source);
  57130. });
  57131. }
  57132. return video;
  57133. };
  57134. ;
  57135. /**
  57136. * Internal method to initiate `update`.
  57137. */
  57138. VideoTexture.prototype._rebuild = function () {
  57139. this.update();
  57140. };
  57141. /**
  57142. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57143. */
  57144. VideoTexture.prototype.update = function () {
  57145. if (!this.autoUpdateTexture) {
  57146. // Expecting user to call `updateTexture` manually
  57147. return;
  57148. }
  57149. this.updateTexture(true);
  57150. };
  57151. /**
  57152. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57153. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57154. */
  57155. VideoTexture.prototype.updateTexture = function (isVisible) {
  57156. if (!isVisible) {
  57157. return;
  57158. }
  57159. if (this.video.paused) {
  57160. return;
  57161. }
  57162. this._updateInternalTexture();
  57163. };
  57164. /**
  57165. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57166. * @param url New url.
  57167. */
  57168. VideoTexture.prototype.updateURL = function (url) {
  57169. this.video.src = url;
  57170. };
  57171. VideoTexture.prototype.dispose = function () {
  57172. _super.prototype.dispose.call(this);
  57173. this.video.removeEventListener("canplay", this._createInternalTexture);
  57174. this.video.removeEventListener("paused", this._updateInternalTexture);
  57175. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57176. this.video.removeEventListener("emptied", this.reset);
  57177. };
  57178. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57179. var video = document.createElement("video");
  57180. var constraintsDeviceId;
  57181. if (constraints && constraints.deviceId) {
  57182. constraintsDeviceId = {
  57183. exact: constraints.deviceId,
  57184. };
  57185. }
  57186. navigator.getUserMedia =
  57187. navigator.getUserMedia ||
  57188. navigator.webkitGetUserMedia ||
  57189. navigator.mozGetUserMedia ||
  57190. navigator.msGetUserMedia;
  57191. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57192. if (navigator.getUserMedia) {
  57193. navigator.getUserMedia({
  57194. video: {
  57195. deviceId: constraintsDeviceId,
  57196. width: {
  57197. min: (constraints && constraints.minWidth) || 256,
  57198. max: (constraints && constraints.maxWidth) || 640,
  57199. },
  57200. height: {
  57201. min: (constraints && constraints.minHeight) || 256,
  57202. max: (constraints && constraints.maxHeight) || 480,
  57203. },
  57204. },
  57205. }, function (stream) {
  57206. if (video.mozSrcObject !== undefined) {
  57207. // hack for Firefox < 19
  57208. video.mozSrcObject = stream;
  57209. }
  57210. else {
  57211. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57212. }
  57213. video.play();
  57214. if (onReady) {
  57215. onReady(new VideoTexture("video", video, scene, true, true));
  57216. }
  57217. }, function (e) {
  57218. BABYLON.Tools.Error(e.name);
  57219. });
  57220. }
  57221. };
  57222. return VideoTexture;
  57223. }(BABYLON.Texture));
  57224. BABYLON.VideoTexture = VideoTexture;
  57225. })(BABYLON || (BABYLON = {}));
  57226. //# sourceMappingURL=babylon.videoTexture.js.map
  57227. var BABYLON;
  57228. (function (BABYLON) {
  57229. var RawTexture = /** @class */ (function (_super) {
  57230. __extends(RawTexture, _super);
  57231. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57232. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57233. if (invertY === void 0) { invertY = false; }
  57234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57235. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57236. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57237. _this.format = format;
  57238. _this._engine = scene.getEngine();
  57239. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57240. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57241. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57242. return _this;
  57243. }
  57244. RawTexture.prototype.update = function (data) {
  57245. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57246. };
  57247. // Statics
  57248. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57250. if (invertY === void 0) { invertY = false; }
  57251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57253. };
  57254. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57256. if (invertY === void 0) { invertY = false; }
  57257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57259. };
  57260. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57262. if (invertY === void 0) { invertY = false; }
  57263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57264. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57265. };
  57266. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57267. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57268. if (invertY === void 0) { invertY = false; }
  57269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57270. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57271. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57272. };
  57273. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57274. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57275. if (invertY === void 0) { invertY = false; }
  57276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57277. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57278. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57279. };
  57280. return RawTexture;
  57281. }(BABYLON.Texture));
  57282. BABYLON.RawTexture = RawTexture;
  57283. })(BABYLON || (BABYLON = {}));
  57284. //# sourceMappingURL=babylon.rawTexture.js.map
  57285. var BABYLON;
  57286. (function (BABYLON) {
  57287. /**
  57288. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57289. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57290. */
  57291. var PostProcess = /** @class */ (function () {
  57292. /**
  57293. * Creates a new instance of @see PostProcess
  57294. * @param name The name of the PostProcess.
  57295. * @param fragmentUrl The url of the fragment shader to be used.
  57296. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57297. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57298. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57299. * @param camera The camera to apply the render pass to.
  57300. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57301. * @param engine The engine which the post process will be applied. (default: current engine)
  57302. * @param reusable If the post process can be reused on the same frame. (default: false)
  57303. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57304. * @param textureType Type of textures used when performing the post process. (default: 0)
  57305. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57306. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  57307. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57308. */
  57309. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57311. if (defines === void 0) { defines = null; }
  57312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57313. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57314. if (blockCompilation === void 0) { blockCompilation = false; }
  57315. this.name = name;
  57316. /**
  57317. * Width of the texture to apply the post process on
  57318. */
  57319. this.width = -1;
  57320. /**
  57321. * Height of the texture to apply the post process on
  57322. */
  57323. this.height = -1;
  57324. /**
  57325. * If the buffer needs to be cleared before applying the post process. (default: true)
  57326. * Should be set to false if shader will overwrite all previous pixels.
  57327. */
  57328. this.autoClear = true;
  57329. /**
  57330. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57331. */
  57332. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57333. /**
  57334. * Animations to be used for the post processing
  57335. */
  57336. this.animations = new Array();
  57337. /**
  57338. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57339. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57340. */
  57341. this.enablePixelPerfectMode = false;
  57342. /**
  57343. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57344. */
  57345. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57346. /**
  57347. * Force textures to be a power of two (default: false)
  57348. */
  57349. this.alwaysForcePOT = false;
  57350. /**
  57351. * Number of sample textures (default: 1)
  57352. */
  57353. this.samples = 1;
  57354. /**
  57355. * Modify the scale of the post process to be the same as the viewport (default: false)
  57356. */
  57357. this.adaptScaleToCurrentViewport = false;
  57358. this._reusable = false;
  57359. /**
  57360. * Smart array of input and output textures for the post process.
  57361. */
  57362. this._textures = new BABYLON.SmartArray(2);
  57363. /**
  57364. * The index in _textures that corresponds to the output texture.
  57365. */
  57366. this._currentRenderTextureInd = 0;
  57367. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57368. this._texelSize = BABYLON.Vector2.Zero();
  57369. // Events
  57370. /**
  57371. * An event triggered when the postprocess is activated.
  57372. * @type {BABYLON.Observable}
  57373. */
  57374. this.onActivateObservable = new BABYLON.Observable();
  57375. /**
  57376. * An event triggered when the postprocess changes its size.
  57377. * @type {BABYLON.Observable}
  57378. */
  57379. this.onSizeChangedObservable = new BABYLON.Observable();
  57380. /**
  57381. * An event triggered when the postprocess applies its effect.
  57382. * @type {BABYLON.Observable}
  57383. */
  57384. this.onApplyObservable = new BABYLON.Observable();
  57385. /**
  57386. * An event triggered before rendering the postprocess
  57387. * @type {BABYLON.Observable}
  57388. */
  57389. this.onBeforeRenderObservable = new BABYLON.Observable();
  57390. /**
  57391. * An event triggered after rendering the postprocess
  57392. * @type {BABYLON.Observable}
  57393. */
  57394. this.onAfterRenderObservable = new BABYLON.Observable();
  57395. if (camera != null) {
  57396. this._camera = camera;
  57397. this._scene = camera.getScene();
  57398. camera.attachPostProcess(this);
  57399. this._engine = this._scene.getEngine();
  57400. this._scene.postProcesses.push(this);
  57401. }
  57402. else if (engine) {
  57403. this._engine = engine;
  57404. this._engine.postProcesses.push(this);
  57405. }
  57406. this._options = options;
  57407. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57408. this._reusable = reusable || false;
  57409. this._textureType = textureType;
  57410. this._samplers = samplers || [];
  57411. this._samplers.push("textureSampler");
  57412. this._fragmentUrl = fragmentUrl;
  57413. this._vertexUrl = vertexUrl;
  57414. this._parameters = parameters || [];
  57415. this._parameters.push("scale");
  57416. this._indexParameters = indexParameters;
  57417. if (!blockCompilation) {
  57418. this.updateEffect(defines);
  57419. }
  57420. }
  57421. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57422. /**
  57423. * A function that is added to the onActivateObservable
  57424. */
  57425. set: function (callback) {
  57426. if (this._onActivateObserver) {
  57427. this.onActivateObservable.remove(this._onActivateObserver);
  57428. }
  57429. if (callback) {
  57430. this._onActivateObserver = this.onActivateObservable.add(callback);
  57431. }
  57432. },
  57433. enumerable: true,
  57434. configurable: true
  57435. });
  57436. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57437. /**
  57438. * A function that is added to the onSizeChangedObservable
  57439. */
  57440. set: function (callback) {
  57441. if (this._onSizeChangedObserver) {
  57442. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57443. }
  57444. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57445. },
  57446. enumerable: true,
  57447. configurable: true
  57448. });
  57449. Object.defineProperty(PostProcess.prototype, "onApply", {
  57450. /**
  57451. * A function that is added to the onApplyObservable
  57452. */
  57453. set: function (callback) {
  57454. if (this._onApplyObserver) {
  57455. this.onApplyObservable.remove(this._onApplyObserver);
  57456. }
  57457. this._onApplyObserver = this.onApplyObservable.add(callback);
  57458. },
  57459. enumerable: true,
  57460. configurable: true
  57461. });
  57462. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57463. /**
  57464. * A function that is added to the onBeforeRenderObservable
  57465. */
  57466. set: function (callback) {
  57467. if (this._onBeforeRenderObserver) {
  57468. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57469. }
  57470. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57471. },
  57472. enumerable: true,
  57473. configurable: true
  57474. });
  57475. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57476. /**
  57477. * A function that is added to the onAfterRenderObservable
  57478. */
  57479. set: function (callback) {
  57480. if (this._onAfterRenderObserver) {
  57481. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57482. }
  57483. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57484. },
  57485. enumerable: true,
  57486. configurable: true
  57487. });
  57488. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57489. /**
  57490. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  57491. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57492. */
  57493. get: function () {
  57494. return this._textures.data[this._currentRenderTextureInd];
  57495. },
  57496. set: function (value) {
  57497. this._forcedOutputTexture = value;
  57498. },
  57499. enumerable: true,
  57500. configurable: true
  57501. });
  57502. /**
  57503. * Gets the camera which post process is applied to.
  57504. * @returns The camera the post process is applied to.
  57505. */
  57506. PostProcess.prototype.getCamera = function () {
  57507. return this._camera;
  57508. };
  57509. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57510. /**
  57511. * Gets the texel size of the postprocess.
  57512. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57513. */
  57514. get: function () {
  57515. if (this._shareOutputWithPostProcess) {
  57516. return this._shareOutputWithPostProcess.texelSize;
  57517. }
  57518. if (this._forcedOutputTexture) {
  57519. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57520. }
  57521. return this._texelSize;
  57522. },
  57523. enumerable: true,
  57524. configurable: true
  57525. });
  57526. /**
  57527. * Gets the engine which this post process belongs to.
  57528. * @returns The engine the post process was enabled with.
  57529. */
  57530. PostProcess.prototype.getEngine = function () {
  57531. return this._engine;
  57532. };
  57533. /**
  57534. * The effect that is created when initializing the post process.
  57535. * @returns The created effect corrisponding the the postprocess.
  57536. */
  57537. PostProcess.prototype.getEffect = function () {
  57538. return this._effect;
  57539. };
  57540. /**
  57541. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57542. * @param postProcess The post process to share the output with.
  57543. * @returns This post process.
  57544. */
  57545. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57546. this._disposeTextures();
  57547. this._shareOutputWithPostProcess = postProcess;
  57548. return this;
  57549. };
  57550. /**
  57551. * Updates the effect with the current post process compile time values and recompiles the shader.
  57552. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57553. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57554. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57555. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  57556. * @param onCompiled Called when the shader has been compiled.
  57557. * @param onError Called if there is an error when compiling a shader.
  57558. */
  57559. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57560. if (defines === void 0) { defines = null; }
  57561. if (uniforms === void 0) { uniforms = null; }
  57562. if (samplers === void 0) { samplers = null; }
  57563. 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);
  57564. };
  57565. /**
  57566. * The post process is reusable if it can be used multiple times within one frame.
  57567. * @returns If the post process is reusable
  57568. */
  57569. PostProcess.prototype.isReusable = function () {
  57570. return this._reusable;
  57571. };
  57572. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57573. PostProcess.prototype.markTextureDirty = function () {
  57574. this.width = -1;
  57575. };
  57576. /**
  57577. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57578. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  57579. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57580. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57581. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57582. */
  57583. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57584. var _this = this;
  57585. if (sourceTexture === void 0) { sourceTexture = null; }
  57586. camera = camera || this._camera;
  57587. var scene = camera.getScene();
  57588. var engine = scene.getEngine();
  57589. var maxSize = engine.getCaps().maxTextureSize;
  57590. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57591. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57592. var desiredWidth = (this._options.width || requiredWidth);
  57593. var desiredHeight = this._options.height || requiredHeight;
  57594. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57595. if (this.adaptScaleToCurrentViewport) {
  57596. var currentViewport = engine.currentViewport;
  57597. if (currentViewport) {
  57598. desiredWidth *= currentViewport.width;
  57599. desiredHeight *= currentViewport.height;
  57600. }
  57601. }
  57602. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57603. if (!this._options.width) {
  57604. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57605. }
  57606. if (!this._options.height) {
  57607. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57608. }
  57609. }
  57610. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57611. if (this._textures.length > 0) {
  57612. for (var i = 0; i < this._textures.length; i++) {
  57613. this._engine._releaseTexture(this._textures.data[i]);
  57614. }
  57615. this._textures.reset();
  57616. }
  57617. this.width = desiredWidth;
  57618. this.height = desiredHeight;
  57619. var textureSize = { width: this.width, height: this.height };
  57620. var textureOptions = {
  57621. generateMipMaps: false,
  57622. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57623. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57624. samplingMode: this.renderTargetSamplingMode,
  57625. type: this._textureType
  57626. };
  57627. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57628. if (this._reusable) {
  57629. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57630. }
  57631. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57632. this.onSizeChangedObservable.notifyObservers(this);
  57633. }
  57634. this._textures.forEach(function (texture) {
  57635. if (texture.samples !== _this.samples) {
  57636. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57637. }
  57638. });
  57639. }
  57640. var target;
  57641. if (this._shareOutputWithPostProcess) {
  57642. target = this._shareOutputWithPostProcess.inputTexture;
  57643. }
  57644. else if (this._forcedOutputTexture) {
  57645. target = this._forcedOutputTexture;
  57646. this.width = this._forcedOutputTexture.width;
  57647. this.height = this._forcedOutputTexture.height;
  57648. }
  57649. else {
  57650. target = this.inputTexture;
  57651. }
  57652. // Bind the input of this post process to be used as the output of the previous post process.
  57653. if (this.enablePixelPerfectMode) {
  57654. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57655. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57656. }
  57657. else {
  57658. this._scaleRatio.copyFromFloats(1, 1);
  57659. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57660. }
  57661. this.onActivateObservable.notifyObservers(camera);
  57662. // Clear
  57663. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57664. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57665. }
  57666. if (this._reusable) {
  57667. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57668. }
  57669. };
  57670. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57671. /**
  57672. * If the post process is supported.
  57673. */
  57674. get: function () {
  57675. return this._effect.isSupported;
  57676. },
  57677. enumerable: true,
  57678. configurable: true
  57679. });
  57680. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57681. /**
  57682. * The aspect ratio of the output texture.
  57683. */
  57684. get: function () {
  57685. if (this._shareOutputWithPostProcess) {
  57686. return this._shareOutputWithPostProcess.aspectRatio;
  57687. }
  57688. if (this._forcedOutputTexture) {
  57689. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57690. }
  57691. return this.width / this.height;
  57692. },
  57693. enumerable: true,
  57694. configurable: true
  57695. });
  57696. /**
  57697. * Get a value indicating if the post-process is ready to be used
  57698. * @returns true if the post-process is ready (shader is compiled)
  57699. */
  57700. PostProcess.prototype.isReady = function () {
  57701. return this._effect && this._effect.isReady();
  57702. };
  57703. /**
  57704. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57705. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57706. */
  57707. PostProcess.prototype.apply = function () {
  57708. // Check
  57709. if (!this._effect || !this._effect.isReady())
  57710. return null;
  57711. // States
  57712. this._engine.enableEffect(this._effect);
  57713. this._engine.setState(false);
  57714. this._engine.setDepthBuffer(false);
  57715. this._engine.setDepthWrite(false);
  57716. // Alpha
  57717. this._engine.setAlphaMode(this.alphaMode);
  57718. if (this.alphaConstants) {
  57719. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57720. }
  57721. // Bind the output texture of the preivous post process as the input to this post process.
  57722. var source;
  57723. if (this._shareOutputWithPostProcess) {
  57724. source = this._shareOutputWithPostProcess.inputTexture;
  57725. }
  57726. else if (this._forcedOutputTexture) {
  57727. source = this._forcedOutputTexture;
  57728. }
  57729. else {
  57730. source = this.inputTexture;
  57731. }
  57732. this._effect._bindTexture("textureSampler", source);
  57733. // Parameters
  57734. this._effect.setVector2("scale", this._scaleRatio);
  57735. this.onApplyObservable.notifyObservers(this._effect);
  57736. return this._effect;
  57737. };
  57738. PostProcess.prototype._disposeTextures = function () {
  57739. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57740. return;
  57741. }
  57742. if (this._textures.length > 0) {
  57743. for (var i = 0; i < this._textures.length; i++) {
  57744. this._engine._releaseTexture(this._textures.data[i]);
  57745. }
  57746. }
  57747. this._textures.dispose();
  57748. };
  57749. /**
  57750. * Disposes the post process.
  57751. * @param camera The camera to dispose the post process on.
  57752. */
  57753. PostProcess.prototype.dispose = function (camera) {
  57754. camera = camera || this._camera;
  57755. this._disposeTextures();
  57756. if (this._scene) {
  57757. var index_1 = this._scene.postProcesses.indexOf(this);
  57758. if (index_1 !== -1) {
  57759. this._scene.postProcesses.splice(index_1, 1);
  57760. }
  57761. }
  57762. else {
  57763. var index_2 = this._engine.postProcesses.indexOf(this);
  57764. if (index_2 !== -1) {
  57765. this._engine.postProcesses.splice(index_2, 1);
  57766. }
  57767. }
  57768. if (!camera) {
  57769. return;
  57770. }
  57771. camera.detachPostProcess(this);
  57772. var index = camera._postProcesses.indexOf(this);
  57773. if (index === 0 && camera._postProcesses.length > 0) {
  57774. this._camera._postProcesses[0].markTextureDirty();
  57775. }
  57776. this.onActivateObservable.clear();
  57777. this.onAfterRenderObservable.clear();
  57778. this.onApplyObservable.clear();
  57779. this.onBeforeRenderObservable.clear();
  57780. this.onSizeChangedObservable.clear();
  57781. };
  57782. return PostProcess;
  57783. }());
  57784. BABYLON.PostProcess = PostProcess;
  57785. })(BABYLON || (BABYLON = {}));
  57786. //# sourceMappingURL=babylon.postProcess.js.map
  57787. var BABYLON;
  57788. (function (BABYLON) {
  57789. var PassPostProcess = /** @class */ (function (_super) {
  57790. __extends(PassPostProcess, _super);
  57791. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57792. if (camera === void 0) { camera = null; }
  57793. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57794. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57795. }
  57796. return PassPostProcess;
  57797. }(BABYLON.PostProcess));
  57798. BABYLON.PassPostProcess = PassPostProcess;
  57799. })(BABYLON || (BABYLON = {}));
  57800. //# sourceMappingURL=babylon.passPostProcess.js.map
  57801. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57802. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57803. s = arguments[i];
  57804. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57805. t[p] = s[p];
  57806. }
  57807. return t;
  57808. };
  57809. var BABYLON;
  57810. (function (BABYLON) {
  57811. /**
  57812. * Default implementation of @see IShadowGenerator.
  57813. * This is the main object responsible of generating shadows in the framework.
  57814. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57815. */
  57816. var ShadowGenerator = /** @class */ (function () {
  57817. /**
  57818. * Creates a ShadowGenerator object.
  57819. * A ShadowGenerator is the required tool to use the shadows.
  57820. * Each light casting shadows needs to use its own ShadowGenerator.
  57821. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57822. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57823. * @param light The light object generating the shadows.
  57824. * @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.
  57825. */
  57826. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57827. this._bias = 0.00005;
  57828. this._blurBoxOffset = 1;
  57829. this._blurScale = 2;
  57830. this._blurKernel = 1;
  57831. this._useKernelBlur = false;
  57832. this._filter = ShadowGenerator.FILTER_NONE;
  57833. this._darkness = 0;
  57834. this._transparencyShadow = false;
  57835. /**
  57836. * Controls the extent to which the shadows fade out at the edge of the frustum
  57837. * Used only by directionals and spots
  57838. */
  57839. this.frustumEdgeFalloff = 0;
  57840. /**
  57841. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57842. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57843. * It might on the other hand introduce peter panning.
  57844. */
  57845. this.forceBackFacesOnly = false;
  57846. this._lightDirection = BABYLON.Vector3.Zero();
  57847. this._viewMatrix = BABYLON.Matrix.Zero();
  57848. this._projectionMatrix = BABYLON.Matrix.Zero();
  57849. this._transformMatrix = BABYLON.Matrix.Zero();
  57850. this._currentFaceIndex = 0;
  57851. this._currentFaceIndexCache = 0;
  57852. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57853. this._mapSize = mapSize;
  57854. this._light = light;
  57855. this._scene = light.getScene();
  57856. light._shadowGenerator = this;
  57857. // Texture type fallback from float to int if not supported.
  57858. var caps = this._scene.getEngine().getCaps();
  57859. if (!useFullFloatFirst) {
  57860. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57861. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57862. }
  57863. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57864. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57865. }
  57866. else {
  57867. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57868. }
  57869. }
  57870. else {
  57871. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57872. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57873. }
  57874. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57875. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57876. }
  57877. else {
  57878. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57879. }
  57880. }
  57881. this._initializeGenerator();
  57882. }
  57883. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  57884. /**
  57885. * Shadow generator mode None: no filtering applied.
  57886. */
  57887. get: function () {
  57888. return ShadowGenerator._FILTER_NONE;
  57889. },
  57890. enumerable: true,
  57891. configurable: true
  57892. });
  57893. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  57894. /**
  57895. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  57896. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  57897. */
  57898. get: function () {
  57899. return ShadowGenerator._FILTER_POISSONSAMPLING;
  57900. },
  57901. enumerable: true,
  57902. configurable: true
  57903. });
  57904. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  57905. /**
  57906. * Shadow generator mode ESM: Exponential Shadow Mapping.
  57907. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57908. */
  57909. get: function () {
  57910. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  57911. },
  57912. enumerable: true,
  57913. configurable: true
  57914. });
  57915. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  57916. /**
  57917. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  57918. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57919. */
  57920. get: function () {
  57921. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  57922. },
  57923. enumerable: true,
  57924. configurable: true
  57925. });
  57926. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  57927. /**
  57928. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  57929. * edge artifacts on steep falloff.
  57930. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57931. */
  57932. get: function () {
  57933. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57934. },
  57935. enumerable: true,
  57936. configurable: true
  57937. });
  57938. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  57939. /**
  57940. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  57941. * edge artifacts on steep falloff.
  57942. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57943. */
  57944. get: function () {
  57945. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57946. },
  57947. enumerable: true,
  57948. configurable: true
  57949. });
  57950. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  57951. /**
  57952. * Gets the bias: offset applied on the depth preventing acnea.
  57953. */
  57954. get: function () {
  57955. return this._bias;
  57956. },
  57957. /**
  57958. * Sets the bias: offset applied on the depth preventing acnea.
  57959. */
  57960. set: function (bias) {
  57961. this._bias = bias;
  57962. },
  57963. enumerable: true,
  57964. configurable: true
  57965. });
  57966. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  57967. /**
  57968. * Gets the blur box offset: offset applied during the blur pass.
  57969. * Only usefull if useKernelBlur = false
  57970. */
  57971. get: function () {
  57972. return this._blurBoxOffset;
  57973. },
  57974. /**
  57975. * Sets the blur box offset: offset applied during the blur pass.
  57976. * Only usefull if useKernelBlur = false
  57977. */
  57978. set: function (value) {
  57979. if (this._blurBoxOffset === value) {
  57980. return;
  57981. }
  57982. this._blurBoxOffset = value;
  57983. this._disposeBlurPostProcesses();
  57984. },
  57985. enumerable: true,
  57986. configurable: true
  57987. });
  57988. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  57989. /**
  57990. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  57991. * 2 means half of the size.
  57992. */
  57993. get: function () {
  57994. return this._blurScale;
  57995. },
  57996. /**
  57997. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  57998. * 2 means half of the size.
  57999. */
  58000. set: function (value) {
  58001. if (this._blurScale === value) {
  58002. return;
  58003. }
  58004. this._blurScale = value;
  58005. this._disposeBlurPostProcesses();
  58006. },
  58007. enumerable: true,
  58008. configurable: true
  58009. });
  58010. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58011. /**
  58012. * Gets the blur kernel: kernel size of the blur pass.
  58013. * Only usefull if useKernelBlur = true
  58014. */
  58015. get: function () {
  58016. return this._blurKernel;
  58017. },
  58018. /**
  58019. * Sets the blur kernel: kernel size of the blur pass.
  58020. * Only usefull if useKernelBlur = true
  58021. */
  58022. set: function (value) {
  58023. if (this._blurKernel === value) {
  58024. return;
  58025. }
  58026. this._blurKernel = value;
  58027. this._disposeBlurPostProcesses();
  58028. },
  58029. enumerable: true,
  58030. configurable: true
  58031. });
  58032. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58033. /**
  58034. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58035. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58036. */
  58037. get: function () {
  58038. return this._useKernelBlur;
  58039. },
  58040. /**
  58041. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58042. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58043. */
  58044. set: function (value) {
  58045. if (this._useKernelBlur === value) {
  58046. return;
  58047. }
  58048. this._useKernelBlur = value;
  58049. this._disposeBlurPostProcesses();
  58050. },
  58051. enumerable: true,
  58052. configurable: true
  58053. });
  58054. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58055. /**
  58056. * Gets the depth scale used in ESM mode.
  58057. */
  58058. get: function () {
  58059. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58060. },
  58061. /**
  58062. * Sets the depth scale used in ESM mode.
  58063. * This can override the scale stored on the light.
  58064. */
  58065. set: function (value) {
  58066. this._depthScale = value;
  58067. },
  58068. enumerable: true,
  58069. configurable: true
  58070. });
  58071. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58072. /**
  58073. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58074. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58075. */
  58076. get: function () {
  58077. return this._filter;
  58078. },
  58079. /**
  58080. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58081. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58082. */
  58083. set: function (value) {
  58084. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58085. if (this._light.needCube()) {
  58086. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58087. this.useExponentialShadowMap = true;
  58088. return;
  58089. }
  58090. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58091. this.useCloseExponentialShadowMap = true;
  58092. return;
  58093. }
  58094. }
  58095. if (this._filter === value) {
  58096. return;
  58097. }
  58098. this._filter = value;
  58099. this._disposeBlurPostProcesses();
  58100. this._applyFilterValues();
  58101. this._light._markMeshesAsLightDirty();
  58102. },
  58103. enumerable: true,
  58104. configurable: true
  58105. });
  58106. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58107. /**
  58108. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58109. */
  58110. get: function () {
  58111. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58112. },
  58113. /**
  58114. * Sets the current filter to Poisson Sampling aka PCF.
  58115. */
  58116. set: function (value) {
  58117. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58118. return;
  58119. }
  58120. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58121. },
  58122. enumerable: true,
  58123. configurable: true
  58124. });
  58125. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58126. /**
  58127. * Gets if the current filter is set to VSM.
  58128. * DEPRECATED. Should use useExponentialShadowMap instead.
  58129. */
  58130. get: function () {
  58131. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58132. return this.useExponentialShadowMap;
  58133. },
  58134. /**
  58135. * Sets the current filter is to VSM.
  58136. * DEPRECATED. Should use useExponentialShadowMap instead.
  58137. */
  58138. set: function (value) {
  58139. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58140. this.useExponentialShadowMap = value;
  58141. },
  58142. enumerable: true,
  58143. configurable: true
  58144. });
  58145. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58146. /**
  58147. * Gets if the current filter is set to blurred VSM.
  58148. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58149. */
  58150. get: function () {
  58151. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58152. return this.useBlurExponentialShadowMap;
  58153. },
  58154. /**
  58155. * Sets the current filter is to blurred VSM.
  58156. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58157. */
  58158. set: function (value) {
  58159. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58160. this.useBlurExponentialShadowMap = value;
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58166. /**
  58167. * Gets if the current filter is set to ESM.
  58168. */
  58169. get: function () {
  58170. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58171. },
  58172. /**
  58173. * Sets the current filter is to ESM.
  58174. */
  58175. set: function (value) {
  58176. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58177. return;
  58178. }
  58179. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58180. },
  58181. enumerable: true,
  58182. configurable: true
  58183. });
  58184. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58185. /**
  58186. * Gets if the current filter is set to filtered ESM.
  58187. */
  58188. get: function () {
  58189. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58190. },
  58191. /**
  58192. * Gets if the current filter is set to filtered ESM.
  58193. */
  58194. set: function (value) {
  58195. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58196. return;
  58197. }
  58198. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58199. },
  58200. enumerable: true,
  58201. configurable: true
  58202. });
  58203. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58204. /**
  58205. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58206. * exponential to prevent steep falloff artifacts).
  58207. */
  58208. get: function () {
  58209. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58210. },
  58211. /**
  58212. * Sets the current filter to "close ESM" (using the inverse of the
  58213. * exponential to prevent steep falloff artifacts).
  58214. */
  58215. set: function (value) {
  58216. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58217. return;
  58218. }
  58219. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58220. },
  58221. enumerable: true,
  58222. configurable: true
  58223. });
  58224. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58225. /**
  58226. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58227. * exponential to prevent steep falloff artifacts).
  58228. */
  58229. get: function () {
  58230. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58231. },
  58232. /**
  58233. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58234. * exponential to prevent steep falloff artifacts).
  58235. */
  58236. set: function (value) {
  58237. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58238. return;
  58239. }
  58240. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58241. },
  58242. enumerable: true,
  58243. configurable: true
  58244. });
  58245. /**
  58246. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58247. * 0 means strongest and 1 would means no shadow.
  58248. * @returns the darkness.
  58249. */
  58250. ShadowGenerator.prototype.getDarkness = function () {
  58251. return this._darkness;
  58252. };
  58253. /**
  58254. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58255. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58256. * @returns the shadow generator allowing fluent coding.
  58257. */
  58258. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58259. if (darkness >= 1.0)
  58260. this._darkness = 1.0;
  58261. else if (darkness <= 0.0)
  58262. this._darkness = 0.0;
  58263. else
  58264. this._darkness = darkness;
  58265. return this;
  58266. };
  58267. /**
  58268. * Sets the ability to have transparent shadow (boolean).
  58269. * @param transparent True if transparent else False
  58270. * @returns the shadow generator allowing fluent coding
  58271. */
  58272. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58273. this._transparencyShadow = transparent;
  58274. return this;
  58275. };
  58276. /**
  58277. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58278. * @returns The render target texture if present otherwise, null
  58279. */
  58280. ShadowGenerator.prototype.getShadowMap = function () {
  58281. return this._shadowMap;
  58282. };
  58283. /**
  58284. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58285. * @returns The render target texture if the shadow map is present otherwise, null
  58286. */
  58287. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58288. if (this._shadowMap2) {
  58289. return this._shadowMap2;
  58290. }
  58291. return this._shadowMap;
  58292. };
  58293. /**
  58294. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58295. * @param mesh Mesh to add
  58296. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58297. * @returns the Shadow Generator itself
  58298. */
  58299. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58300. if (includeDescendants === void 0) { includeDescendants = true; }
  58301. if (!this._shadowMap) {
  58302. return this;
  58303. }
  58304. if (!this._shadowMap.renderList) {
  58305. this._shadowMap.renderList = [];
  58306. }
  58307. this._shadowMap.renderList.push(mesh);
  58308. if (includeDescendants) {
  58309. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58310. }
  58311. return this;
  58312. var _a;
  58313. };
  58314. /**
  58315. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58316. * @param mesh Mesh to remove
  58317. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58318. * @returns the Shadow Generator itself
  58319. */
  58320. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58321. if (includeDescendants === void 0) { includeDescendants = true; }
  58322. if (!this._shadowMap || !this._shadowMap.renderList) {
  58323. return this;
  58324. }
  58325. var index = this._shadowMap.renderList.indexOf(mesh);
  58326. if (index !== -1) {
  58327. this._shadowMap.renderList.splice(index, 1);
  58328. }
  58329. if (includeDescendants) {
  58330. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58331. var child = _a[_i];
  58332. this.removeShadowCaster(child);
  58333. }
  58334. }
  58335. return this;
  58336. };
  58337. /**
  58338. * Returns the associated light object.
  58339. * @returns the light generating the shadow
  58340. */
  58341. ShadowGenerator.prototype.getLight = function () {
  58342. return this._light;
  58343. };
  58344. ShadowGenerator.prototype._initializeGenerator = function () {
  58345. this._light._markMeshesAsLightDirty();
  58346. this._initializeShadowMap();
  58347. };
  58348. ShadowGenerator.prototype._initializeShadowMap = function () {
  58349. var _this = this;
  58350. // Render target
  58351. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58352. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58353. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58354. this._shadowMap.anisotropicFilteringLevel = 1;
  58355. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58356. this._shadowMap.renderParticles = false;
  58357. this._shadowMap.ignoreCameraViewport = true;
  58358. // Record Face Index before render.
  58359. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58360. _this._currentFaceIndex = faceIndex;
  58361. });
  58362. // Custom render function.
  58363. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58364. // Blur if required afer render.
  58365. this._shadowMap.onAfterUnbindObservable.add(function () {
  58366. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58367. return;
  58368. }
  58369. var shadowMap = _this.getShadowMapForRendering();
  58370. if (shadowMap) {
  58371. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58372. }
  58373. });
  58374. // Clear according to the chosen filter.
  58375. this._shadowMap.onClearObservable.add(function (engine) {
  58376. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58377. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58378. }
  58379. else {
  58380. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58381. }
  58382. });
  58383. };
  58384. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58385. var _this = this;
  58386. var engine = this._scene.getEngine();
  58387. var targetSize = this._mapSize / this.blurScale;
  58388. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58389. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58390. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58391. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58392. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58393. }
  58394. if (this.useKernelBlur) {
  58395. 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);
  58396. this._kernelBlurXPostprocess.width = targetSize;
  58397. this._kernelBlurXPostprocess.height = targetSize;
  58398. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58399. effect.setTexture("textureSampler", _this._shadowMap);
  58400. });
  58401. 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);
  58402. this._kernelBlurXPostprocess.autoClear = false;
  58403. this._kernelBlurYPostprocess.autoClear = false;
  58404. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58405. this._kernelBlurXPostprocess.packedFloat = true;
  58406. this._kernelBlurYPostprocess.packedFloat = true;
  58407. }
  58408. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58409. }
  58410. else {
  58411. 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);
  58412. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58413. effect.setFloat2("screenSize", targetSize, targetSize);
  58414. effect.setTexture("textureSampler", _this._shadowMap);
  58415. });
  58416. this._boxBlurPostprocess.autoClear = false;
  58417. this._blurPostProcesses = [this._boxBlurPostprocess];
  58418. }
  58419. };
  58420. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58421. var index;
  58422. var engine = this._scene.getEngine();
  58423. if (depthOnlySubMeshes.length) {
  58424. engine.setColorWrite(false);
  58425. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58426. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58427. }
  58428. engine.setColorWrite(true);
  58429. }
  58430. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58431. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58432. }
  58433. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58434. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58435. }
  58436. if (this._transparencyShadow) {
  58437. for (index = 0; index < transparentSubMeshes.length; index++) {
  58438. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58439. }
  58440. }
  58441. };
  58442. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58443. var _this = this;
  58444. var mesh = subMesh.getRenderingMesh();
  58445. var scene = this._scene;
  58446. var engine = scene.getEngine();
  58447. var material = subMesh.getMaterial();
  58448. if (!material) {
  58449. return;
  58450. }
  58451. // Culling
  58452. engine.setState(material.backFaceCulling);
  58453. // Managing instances
  58454. var batch = mesh._getInstancesRenderList(subMesh._id);
  58455. if (batch.mustReturn) {
  58456. return;
  58457. }
  58458. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58459. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58460. engine.enableEffect(this._effect);
  58461. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58462. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58463. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58464. this._effect.setVector3("lightPosition", this.getLight().position);
  58465. if (scene.activeCamera) {
  58466. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58467. }
  58468. // Alpha test
  58469. if (material && material.needAlphaTesting()) {
  58470. var alphaTexture = material.getAlphaTestTexture();
  58471. if (alphaTexture) {
  58472. this._effect.setTexture("diffuseSampler", alphaTexture);
  58473. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58474. }
  58475. }
  58476. // Bones
  58477. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58478. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58479. }
  58480. if (this.forceBackFacesOnly) {
  58481. engine.setState(true, 0, false, true);
  58482. }
  58483. // Draw
  58484. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58485. if (this.forceBackFacesOnly) {
  58486. engine.setState(true, 0, false, false);
  58487. }
  58488. }
  58489. else {
  58490. // Need to reset refresh rate of the shadowMap
  58491. if (this._shadowMap) {
  58492. this._shadowMap.resetRefreshCounter();
  58493. }
  58494. }
  58495. };
  58496. ShadowGenerator.prototype._applyFilterValues = function () {
  58497. if (!this._shadowMap) {
  58498. return;
  58499. }
  58500. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58501. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58502. }
  58503. else {
  58504. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58505. }
  58506. };
  58507. /**
  58508. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58509. * @param onCompiled Callback triggered at the and of the effects compilation
  58510. * @param options Sets of optional options forcing the compilation with different modes
  58511. */
  58512. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58513. var _this = this;
  58514. var localOptions = __assign({ useInstances: false }, options);
  58515. var shadowMap = this.getShadowMap();
  58516. if (!shadowMap) {
  58517. if (onCompiled) {
  58518. onCompiled(this);
  58519. }
  58520. return;
  58521. }
  58522. var renderList = shadowMap.renderList;
  58523. if (!renderList) {
  58524. if (onCompiled) {
  58525. onCompiled(this);
  58526. }
  58527. return;
  58528. }
  58529. var subMeshes = new Array();
  58530. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58531. var mesh = renderList_1[_i];
  58532. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58533. }
  58534. if (subMeshes.length === 0) {
  58535. if (onCompiled) {
  58536. onCompiled(this);
  58537. }
  58538. return;
  58539. }
  58540. var currentIndex = 0;
  58541. var checkReady = function () {
  58542. if (!_this._scene || !_this._scene.getEngine()) {
  58543. return;
  58544. }
  58545. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58546. currentIndex++;
  58547. if (currentIndex >= subMeshes.length) {
  58548. if (onCompiled) {
  58549. onCompiled(_this);
  58550. }
  58551. return;
  58552. }
  58553. }
  58554. setTimeout(checkReady, 16);
  58555. };
  58556. checkReady();
  58557. };
  58558. /**
  58559. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58560. * @param options Sets of optional options forcing the compilation with different modes
  58561. * @returns A promise that resolves when the compilation completes
  58562. */
  58563. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58564. var _this = this;
  58565. return new Promise(function (resolve) {
  58566. _this.forceCompilation(function () {
  58567. resolve();
  58568. }, options);
  58569. });
  58570. };
  58571. /**
  58572. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58573. * @param subMesh The submesh we want to render in the shadow map
  58574. * @param useInstances Defines wether will draw in the map using instances
  58575. * @returns true if ready otherwise, false
  58576. */
  58577. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58578. var defines = [];
  58579. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58580. defines.push("#define FLOAT");
  58581. }
  58582. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58583. defines.push("#define ESM");
  58584. }
  58585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58586. var mesh = subMesh.getMesh();
  58587. var material = subMesh.getMaterial();
  58588. // Alpha test
  58589. if (material && material.needAlphaTesting()) {
  58590. var alphaTexture = material.getAlphaTestTexture();
  58591. if (alphaTexture) {
  58592. defines.push("#define ALPHATEST");
  58593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58594. attribs.push(BABYLON.VertexBuffer.UVKind);
  58595. defines.push("#define UV1");
  58596. }
  58597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58598. if (alphaTexture.coordinatesIndex === 1) {
  58599. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58600. defines.push("#define UV2");
  58601. }
  58602. }
  58603. }
  58604. }
  58605. // Bones
  58606. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58607. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58608. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58609. if (mesh.numBoneInfluencers > 4) {
  58610. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58611. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58612. }
  58613. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58614. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58615. }
  58616. else {
  58617. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58618. }
  58619. // Instances
  58620. if (useInstances) {
  58621. defines.push("#define INSTANCES");
  58622. attribs.push("world0");
  58623. attribs.push("world1");
  58624. attribs.push("world2");
  58625. attribs.push("world3");
  58626. }
  58627. // Get correct effect
  58628. var join = defines.join("\n");
  58629. if (this._cachedDefines !== join) {
  58630. this._cachedDefines = join;
  58631. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58632. }
  58633. if (!this._effect.isReady()) {
  58634. return false;
  58635. }
  58636. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58637. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58638. this._initializeBlurRTTAndPostProcesses();
  58639. }
  58640. }
  58641. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58642. return false;
  58643. }
  58644. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58645. return false;
  58646. }
  58647. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58648. return false;
  58649. }
  58650. return true;
  58651. };
  58652. /**
  58653. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58654. * @param defines Defines of the material we want to update
  58655. * @param lightIndex Index of the light in the enabled light list of the material
  58656. */
  58657. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58658. var scene = this._scene;
  58659. var light = this._light;
  58660. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58661. return;
  58662. }
  58663. defines["SHADOW" + lightIndex] = true;
  58664. if (this.usePoissonSampling) {
  58665. defines["SHADOWPCF" + lightIndex] = true;
  58666. }
  58667. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58668. defines["SHADOWESM" + lightIndex] = true;
  58669. }
  58670. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58671. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58672. }
  58673. if (light.needCube()) {
  58674. defines["SHADOWCUBE" + lightIndex] = true;
  58675. }
  58676. };
  58677. /**
  58678. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58679. * defined in the generator but impacting the effect).
  58680. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58681. * @param effect The effect we are binfing the information for
  58682. */
  58683. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58684. var light = this._light;
  58685. var scene = this._scene;
  58686. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58687. return;
  58688. }
  58689. var camera = scene.activeCamera;
  58690. if (!camera) {
  58691. return;
  58692. }
  58693. var shadowMap = this.getShadowMap();
  58694. if (!shadowMap) {
  58695. return;
  58696. }
  58697. if (!light.needCube()) {
  58698. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58699. }
  58700. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58701. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58702. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58703. };
  58704. /**
  58705. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58706. * (eq to shadow prjection matrix * light transform matrix)
  58707. * @returns The transform matrix used to create the shadow map
  58708. */
  58709. ShadowGenerator.prototype.getTransformMatrix = function () {
  58710. var scene = this._scene;
  58711. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58712. return this._transformMatrix;
  58713. }
  58714. this._currentRenderID = scene.getRenderId();
  58715. this._currentFaceIndexCache = this._currentFaceIndex;
  58716. var lightPosition = this._light.position;
  58717. if (this._light.computeTransformedInformation()) {
  58718. lightPosition = this._light.transformedPosition;
  58719. }
  58720. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58721. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58722. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58723. }
  58724. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58725. this._cachedPosition = lightPosition.clone();
  58726. this._cachedDirection = this._lightDirection.clone();
  58727. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58728. var shadowMap = this.getShadowMap();
  58729. if (shadowMap) {
  58730. var renderList = shadowMap.renderList;
  58731. if (renderList) {
  58732. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58733. }
  58734. }
  58735. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58736. }
  58737. return this._transformMatrix;
  58738. };
  58739. /**
  58740. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58741. * Cube and 2D textures for instance.
  58742. */
  58743. ShadowGenerator.prototype.recreateShadowMap = function () {
  58744. var shadowMap = this._shadowMap;
  58745. if (!shadowMap) {
  58746. return;
  58747. }
  58748. // Track render list.
  58749. var renderList = shadowMap.renderList;
  58750. // Clean up existing data.
  58751. this._disposeRTTandPostProcesses();
  58752. // Reinitializes.
  58753. this._initializeGenerator();
  58754. // Reaffect the filter to ensure a correct fallback if necessary.
  58755. this.filter = this.filter;
  58756. // Reaffect the filter.
  58757. this._applyFilterValues();
  58758. // Reaffect Render List.
  58759. this._shadowMap.renderList = renderList;
  58760. };
  58761. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58762. if (this._shadowMap2) {
  58763. this._shadowMap2.dispose();
  58764. this._shadowMap2 = null;
  58765. }
  58766. if (this._boxBlurPostprocess) {
  58767. this._boxBlurPostprocess.dispose();
  58768. this._boxBlurPostprocess = null;
  58769. }
  58770. if (this._kernelBlurXPostprocess) {
  58771. this._kernelBlurXPostprocess.dispose();
  58772. this._kernelBlurXPostprocess = null;
  58773. }
  58774. if (this._kernelBlurYPostprocess) {
  58775. this._kernelBlurYPostprocess.dispose();
  58776. this._kernelBlurYPostprocess = null;
  58777. }
  58778. this._blurPostProcesses = [];
  58779. };
  58780. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58781. if (this._shadowMap) {
  58782. this._shadowMap.dispose();
  58783. this._shadowMap = null;
  58784. }
  58785. this._disposeBlurPostProcesses();
  58786. };
  58787. /**
  58788. * Disposes the ShadowGenerator.
  58789. * Returns nothing.
  58790. */
  58791. ShadowGenerator.prototype.dispose = function () {
  58792. this._disposeRTTandPostProcesses();
  58793. if (this._light) {
  58794. this._light._shadowGenerator = null;
  58795. this._light._markMeshesAsLightDirty();
  58796. }
  58797. };
  58798. /**
  58799. * Serializes the shadow generator setup to a json object.
  58800. * @returns The serialized JSON object
  58801. */
  58802. ShadowGenerator.prototype.serialize = function () {
  58803. var serializationObject = {};
  58804. var shadowMap = this.getShadowMap();
  58805. if (!shadowMap) {
  58806. return serializationObject;
  58807. }
  58808. serializationObject.lightId = this._light.id;
  58809. serializationObject.mapSize = shadowMap.getRenderSize();
  58810. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58811. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58812. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58813. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58814. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58815. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58816. serializationObject.depthScale = this.depthScale;
  58817. serializationObject.darkness = this.getDarkness();
  58818. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58819. serializationObject.blurKernel = this.blurKernel;
  58820. serializationObject.blurScale = this.blurScale;
  58821. serializationObject.useKernelBlur = this.useKernelBlur;
  58822. serializationObject.transparencyShadow = this._transparencyShadow;
  58823. serializationObject.renderList = [];
  58824. if (shadowMap.renderList) {
  58825. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58826. var mesh = shadowMap.renderList[meshIndex];
  58827. serializationObject.renderList.push(mesh.id);
  58828. }
  58829. }
  58830. return serializationObject;
  58831. };
  58832. /**
  58833. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58834. * @param parsedShadowGenerator The JSON object to parse
  58835. * @param scene The scene to create the shadow map for
  58836. * @returns The parsed shadow generator
  58837. */
  58838. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58839. //casting to point light, as light is missing the position attr and typescript complains.
  58840. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58841. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58842. var shadowMap = shadowGenerator.getShadowMap();
  58843. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58844. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58845. meshes.forEach(function (mesh) {
  58846. if (!shadowMap) {
  58847. return;
  58848. }
  58849. if (!shadowMap.renderList) {
  58850. shadowMap.renderList = [];
  58851. }
  58852. shadowMap.renderList.push(mesh);
  58853. });
  58854. }
  58855. if (parsedShadowGenerator.usePoissonSampling) {
  58856. shadowGenerator.usePoissonSampling = true;
  58857. }
  58858. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58859. shadowGenerator.useExponentialShadowMap = true;
  58860. }
  58861. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58862. shadowGenerator.useBlurExponentialShadowMap = true;
  58863. }
  58864. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58865. shadowGenerator.useCloseExponentialShadowMap = true;
  58866. }
  58867. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58868. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58869. }
  58870. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58871. shadowGenerator.useExponentialShadowMap = true;
  58872. }
  58873. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58874. shadowGenerator.useBlurExponentialShadowMap = true;
  58875. }
  58876. if (parsedShadowGenerator.depthScale) {
  58877. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  58878. }
  58879. if (parsedShadowGenerator.blurScale) {
  58880. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  58881. }
  58882. if (parsedShadowGenerator.blurBoxOffset) {
  58883. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  58884. }
  58885. if (parsedShadowGenerator.useKernelBlur) {
  58886. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  58887. }
  58888. if (parsedShadowGenerator.blurKernel) {
  58889. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  58890. }
  58891. if (parsedShadowGenerator.bias !== undefined) {
  58892. shadowGenerator.bias = parsedShadowGenerator.bias;
  58893. }
  58894. if (parsedShadowGenerator.darkness) {
  58895. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  58896. }
  58897. if (parsedShadowGenerator.transparencyShadow) {
  58898. shadowGenerator.setTransparencyShadow(true);
  58899. }
  58900. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  58901. return shadowGenerator;
  58902. };
  58903. ShadowGenerator._FILTER_NONE = 0;
  58904. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  58905. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  58906. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  58907. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  58908. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  58909. return ShadowGenerator;
  58910. }());
  58911. BABYLON.ShadowGenerator = ShadowGenerator;
  58912. })(BABYLON || (BABYLON = {}));
  58913. //# sourceMappingURL=babylon.shadowGenerator.js.map
  58914. var BABYLON;
  58915. (function (BABYLON) {
  58916. var DefaultLoadingScreen = /** @class */ (function () {
  58917. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  58918. if (_loadingText === void 0) { _loadingText = ""; }
  58919. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  58920. var _this = this;
  58921. this._renderingCanvas = _renderingCanvas;
  58922. this._loadingText = _loadingText;
  58923. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  58924. // Resize
  58925. this._resizeLoadingUI = function () {
  58926. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  58927. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  58928. if (!_this._loadingDiv) {
  58929. return;
  58930. }
  58931. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  58932. _this._loadingDiv.style.left = canvasRect.left + "px";
  58933. _this._loadingDiv.style.top = canvasRect.top + "px";
  58934. _this._loadingDiv.style.width = canvasRect.width + "px";
  58935. _this._loadingDiv.style.height = canvasRect.height + "px";
  58936. };
  58937. }
  58938. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  58939. if (this._loadingDiv) {
  58940. // Do not add a loading screen if there is already one
  58941. return;
  58942. }
  58943. this._loadingDiv = document.createElement("div");
  58944. this._loadingDiv.id = "babylonjsLoadingDiv";
  58945. this._loadingDiv.style.opacity = "0";
  58946. this._loadingDiv.style.transition = "opacity 1.5s ease";
  58947. this._loadingDiv.style.pointerEvents = "none";
  58948. // Loading text
  58949. this._loadingTextDiv = document.createElement("div");
  58950. this._loadingTextDiv.style.position = "absolute";
  58951. this._loadingTextDiv.style.left = "0";
  58952. this._loadingTextDiv.style.top = "50%";
  58953. this._loadingTextDiv.style.marginTop = "80px";
  58954. this._loadingTextDiv.style.width = "100%";
  58955. this._loadingTextDiv.style.height = "20px";
  58956. this._loadingTextDiv.style.fontFamily = "Arial";
  58957. this._loadingTextDiv.style.fontSize = "14px";
  58958. this._loadingTextDiv.style.color = "white";
  58959. this._loadingTextDiv.style.textAlign = "center";
  58960. this._loadingTextDiv.innerHTML = "Loading";
  58961. this._loadingDiv.appendChild(this._loadingTextDiv);
  58962. //set the predefined text
  58963. this._loadingTextDiv.innerHTML = this._loadingText;
  58964. // Generating keyframes
  58965. var style = document.createElement('style');
  58966. style.type = 'text/css';
  58967. 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 }";
  58968. style.innerHTML = keyFrames;
  58969. document.getElementsByTagName('head')[0].appendChild(style);
  58970. // Loading img
  58971. var imgBack = new Image();
  58972. 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";
  58973. imgBack.style.position = "absolute";
  58974. imgBack.style.left = "50%";
  58975. imgBack.style.top = "50%";
  58976. imgBack.style.marginLeft = "-60px";
  58977. imgBack.style.marginTop = "-60px";
  58978. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  58979. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  58980. imgBack.style.transformOrigin = "50% 50%";
  58981. imgBack.style.webkitTransformOrigin = "50% 50%";
  58982. this._loadingDiv.appendChild(imgBack);
  58983. this._resizeLoadingUI();
  58984. window.addEventListener("resize", this._resizeLoadingUI);
  58985. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  58986. document.body.appendChild(this._loadingDiv);
  58987. this._loadingDiv.style.opacity = "1";
  58988. };
  58989. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  58990. var _this = this;
  58991. if (!this._loadingDiv) {
  58992. return;
  58993. }
  58994. var onTransitionEnd = function () {
  58995. if (!_this._loadingDiv) {
  58996. return;
  58997. }
  58998. document.body.removeChild(_this._loadingDiv);
  58999. window.removeEventListener("resize", _this._resizeLoadingUI);
  59000. _this._loadingDiv = null;
  59001. };
  59002. this._loadingDiv.style.opacity = "0";
  59003. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59004. };
  59005. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59006. set: function (text) {
  59007. this._loadingText = text;
  59008. if (this._loadingTextDiv) {
  59009. this._loadingTextDiv.innerHTML = this._loadingText;
  59010. }
  59011. },
  59012. enumerable: true,
  59013. configurable: true
  59014. });
  59015. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59016. get: function () {
  59017. return this._loadingDivBackgroundColor;
  59018. },
  59019. set: function (color) {
  59020. this._loadingDivBackgroundColor = color;
  59021. if (!this._loadingDiv) {
  59022. return;
  59023. }
  59024. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59025. },
  59026. enumerable: true,
  59027. configurable: true
  59028. });
  59029. return DefaultLoadingScreen;
  59030. }());
  59031. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59032. })(BABYLON || (BABYLON = {}));
  59033. //# sourceMappingURL=babylon.loadingScreen.js.map
  59034. var BABYLON;
  59035. (function (BABYLON) {
  59036. var SceneLoaderProgressEvent = /** @class */ (function () {
  59037. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59038. this.lengthComputable = lengthComputable;
  59039. this.loaded = loaded;
  59040. this.total = total;
  59041. }
  59042. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59043. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59044. };
  59045. return SceneLoaderProgressEvent;
  59046. }());
  59047. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59048. var SceneLoader = /** @class */ (function () {
  59049. function SceneLoader() {
  59050. }
  59051. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59052. get: function () {
  59053. return 0;
  59054. },
  59055. enumerable: true,
  59056. configurable: true
  59057. });
  59058. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59059. get: function () {
  59060. return 1;
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59066. get: function () {
  59067. return 2;
  59068. },
  59069. enumerable: true,
  59070. configurable: true
  59071. });
  59072. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59073. get: function () {
  59074. return 3;
  59075. },
  59076. enumerable: true,
  59077. configurable: true
  59078. });
  59079. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59080. get: function () {
  59081. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59082. },
  59083. set: function (value) {
  59084. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59085. },
  59086. enumerable: true,
  59087. configurable: true
  59088. });
  59089. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59090. get: function () {
  59091. return SceneLoader._ShowLoadingScreen;
  59092. },
  59093. set: function (value) {
  59094. SceneLoader._ShowLoadingScreen = value;
  59095. },
  59096. enumerable: true,
  59097. configurable: true
  59098. });
  59099. Object.defineProperty(SceneLoader, "loggingLevel", {
  59100. get: function () {
  59101. return SceneLoader._loggingLevel;
  59102. },
  59103. set: function (value) {
  59104. SceneLoader._loggingLevel = value;
  59105. },
  59106. enumerable: true,
  59107. configurable: true
  59108. });
  59109. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59110. get: function () {
  59111. return SceneLoader._CleanBoneMatrixWeights;
  59112. },
  59113. set: function (value) {
  59114. SceneLoader._CleanBoneMatrixWeights = value;
  59115. },
  59116. enumerable: true,
  59117. configurable: true
  59118. });
  59119. SceneLoader._getDefaultPlugin = function () {
  59120. return SceneLoader._registeredPlugins[".babylon"];
  59121. };
  59122. SceneLoader._getPluginForExtension = function (extension) {
  59123. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59124. if (registeredPlugin) {
  59125. return registeredPlugin;
  59126. }
  59127. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59128. return SceneLoader._getDefaultPlugin();
  59129. };
  59130. SceneLoader._getPluginForDirectLoad = function (data) {
  59131. for (var extension in SceneLoader._registeredPlugins) {
  59132. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59133. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59134. return SceneLoader._registeredPlugins[extension];
  59135. }
  59136. }
  59137. return SceneLoader._getDefaultPlugin();
  59138. };
  59139. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59140. if (sceneFilename.name) {
  59141. sceneFilename = sceneFilename.name;
  59142. }
  59143. var queryStringPosition = sceneFilename.indexOf("?");
  59144. if (queryStringPosition !== -1) {
  59145. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59146. }
  59147. var dotPosition = sceneFilename.lastIndexOf(".");
  59148. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59149. return SceneLoader._getPluginForExtension(extension);
  59150. };
  59151. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59152. SceneLoader._getDirectLoad = function (sceneFilename) {
  59153. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59154. return sceneFilename.substr(5);
  59155. }
  59156. return null;
  59157. };
  59158. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59159. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59160. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59161. var plugin;
  59162. if (registeredPlugin.plugin.createPlugin) {
  59163. plugin = registeredPlugin.plugin.createPlugin();
  59164. }
  59165. else {
  59166. plugin = registeredPlugin.plugin;
  59167. }
  59168. var useArrayBuffer = registeredPlugin.isBinary;
  59169. var database;
  59170. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59171. var dataCallback = function (data, responseURL) {
  59172. if (scene.isDisposed) {
  59173. onError("Scene has been disposed");
  59174. return;
  59175. }
  59176. scene.database = database;
  59177. onSuccess(plugin, data, responseURL);
  59178. };
  59179. var request = null;
  59180. var pluginDisposed = false;
  59181. var onDisposeObservable = plugin.onDisposeObservable;
  59182. if (onDisposeObservable) {
  59183. onDisposeObservable.add(function () {
  59184. pluginDisposed = true;
  59185. if (request) {
  59186. request.abort();
  59187. request = null;
  59188. }
  59189. onDispose();
  59190. });
  59191. }
  59192. var manifestChecked = function () {
  59193. if (pluginDisposed) {
  59194. return;
  59195. }
  59196. var url = rootUrl + sceneFilename;
  59197. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59198. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59199. } : undefined, database, useArrayBuffer, function (request, exception) {
  59200. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59201. });
  59202. };
  59203. if (directLoad) {
  59204. dataCallback(directLoad);
  59205. return plugin;
  59206. }
  59207. if (rootUrl.indexOf("file:") === -1) {
  59208. if (scene.getEngine().enableOfflineSupport) {
  59209. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59210. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59211. }
  59212. else {
  59213. manifestChecked();
  59214. }
  59215. }
  59216. else {
  59217. var fileOrString = sceneFilename;
  59218. if (fileOrString.name) {
  59219. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59220. }
  59221. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59222. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59223. }
  59224. else {
  59225. onError("Unable to find file named " + sceneFilename);
  59226. }
  59227. }
  59228. return plugin;
  59229. };
  59230. // Public functions
  59231. SceneLoader.GetPluginForExtension = function (extension) {
  59232. return SceneLoader._getPluginForExtension(extension).plugin;
  59233. };
  59234. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59235. return !!SceneLoader._registeredPlugins[extension];
  59236. };
  59237. SceneLoader.RegisterPlugin = function (plugin) {
  59238. if (typeof plugin.extensions === "string") {
  59239. var extension = plugin.extensions;
  59240. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59241. plugin: plugin,
  59242. isBinary: false
  59243. };
  59244. }
  59245. else {
  59246. var extensions = plugin.extensions;
  59247. Object.keys(extensions).forEach(function (extension) {
  59248. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59249. plugin: plugin,
  59250. isBinary: extensions[extension].isBinary
  59251. };
  59252. });
  59253. }
  59254. };
  59255. /**
  59256. * Import meshes into a scene
  59257. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59258. * @param rootUrl a string that defines the root url for scene and resources
  59259. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59260. * @param scene the instance of BABYLON.Scene to append to
  59261. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59262. * @param onProgress a callback with a progress event for each file being loaded
  59263. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59264. * @param pluginExtension the extension used to determine the plugin
  59265. * @returns The loaded plugin
  59266. */
  59267. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59268. if (onSuccess === void 0) { onSuccess = null; }
  59269. if (onProgress === void 0) { onProgress = null; }
  59270. if (onError === void 0) { onError = null; }
  59271. if (pluginExtension === void 0) { pluginExtension = null; }
  59272. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59273. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59274. return null;
  59275. }
  59276. var loadingToken = {};
  59277. scene._addPendingData(loadingToken);
  59278. var disposeHandler = function () {
  59279. scene._removePendingData(loadingToken);
  59280. };
  59281. var errorHandler = function (message, exception) {
  59282. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59283. if (onError) {
  59284. onError(scene, errorMessage, exception);
  59285. }
  59286. else {
  59287. BABYLON.Tools.Error(errorMessage);
  59288. // should the exception be thrown?
  59289. }
  59290. disposeHandler();
  59291. };
  59292. var progressHandler = onProgress ? function (event) {
  59293. try {
  59294. onProgress(event);
  59295. }
  59296. catch (e) {
  59297. errorHandler("Error in onProgress callback", e);
  59298. }
  59299. } : undefined;
  59300. var successHandler = function (meshes, particleSystems, skeletons) {
  59301. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59302. if (onSuccess) {
  59303. try {
  59304. onSuccess(meshes, particleSystems, skeletons);
  59305. }
  59306. catch (e) {
  59307. errorHandler("Error in onSuccess callback", e);
  59308. }
  59309. }
  59310. scene._removePendingData(loadingToken);
  59311. };
  59312. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59313. if (plugin.rewriteRootURL) {
  59314. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59315. }
  59316. if (sceneFilename === "") {
  59317. if (sceneFilename === "") {
  59318. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59319. }
  59320. }
  59321. if (plugin.importMesh) {
  59322. var syncedPlugin = plugin;
  59323. var meshes = new Array();
  59324. var particleSystems = new Array();
  59325. var skeletons = new Array();
  59326. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59327. return;
  59328. }
  59329. scene.loadingPluginName = plugin.name;
  59330. successHandler(meshes, particleSystems, skeletons);
  59331. }
  59332. else {
  59333. var asyncedPlugin = plugin;
  59334. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59335. scene.loadingPluginName = plugin.name;
  59336. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59337. }).catch(function (error) {
  59338. errorHandler(error.message, error);
  59339. });
  59340. }
  59341. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59342. };
  59343. /**
  59344. * Import meshes into a scene
  59345. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59346. * @param rootUrl a string that defines the root url for scene and resources
  59347. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59348. * @param scene the instance of BABYLON.Scene to append to
  59349. * @param onProgress a callback with a progress event for each file being loaded
  59350. * @param pluginExtension the extension used to determine the plugin
  59351. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59352. */
  59353. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59354. if (onProgress === void 0) { onProgress = null; }
  59355. if (pluginExtension === void 0) { pluginExtension = null; }
  59356. return new Promise(function (resolve, reject) {
  59357. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59358. resolve({
  59359. meshes: meshes,
  59360. particleSystems: particleSystems,
  59361. skeletons: skeletons
  59362. });
  59363. }, onProgress, function (scene, message, exception) {
  59364. reject(exception || new Error(message));
  59365. });
  59366. });
  59367. };
  59368. /**
  59369. * Load a scene
  59370. * @param rootUrl a string that defines the root url for scene and resources
  59371. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59372. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59373. * @param onSuccess a callback with the scene when import succeeds
  59374. * @param onProgress a callback with a progress event for each file being loaded
  59375. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59376. * @param pluginExtension the extension used to determine the plugin
  59377. * @returns The loaded plugin
  59378. */
  59379. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59380. if (onSuccess === void 0) { onSuccess = null; }
  59381. if (onProgress === void 0) { onProgress = null; }
  59382. if (onError === void 0) { onError = null; }
  59383. if (pluginExtension === void 0) { pluginExtension = null; }
  59384. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59385. };
  59386. /**
  59387. * Load a scene
  59388. * @param rootUrl a string that defines the root url for scene and resources
  59389. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59390. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59391. * @param onProgress a callback with a progress event for each file being loaded
  59392. * @param pluginExtension the extension used to determine the plugin
  59393. * @returns The loaded scene
  59394. */
  59395. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59396. if (onProgress === void 0) { onProgress = null; }
  59397. if (pluginExtension === void 0) { pluginExtension = null; }
  59398. return new Promise(function (resolve, reject) {
  59399. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59400. resolve(scene);
  59401. }, onProgress, function (scene, message, exception) {
  59402. reject(exception || new Error(message));
  59403. }, pluginExtension);
  59404. });
  59405. };
  59406. /**
  59407. * Append a scene
  59408. * @param rootUrl a string that defines the root url for scene and resources
  59409. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59410. * @param scene is the instance of BABYLON.Scene to append to
  59411. * @param onSuccess a callback with the scene when import succeeds
  59412. * @param onProgress a callback with a progress event for each file being loaded
  59413. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59414. * @param pluginExtension the extension used to determine the plugin
  59415. * @returns The loaded plugin
  59416. */
  59417. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59418. if (onSuccess === void 0) { onSuccess = null; }
  59419. if (onProgress === void 0) { onProgress = null; }
  59420. if (onError === void 0) { onError = null; }
  59421. if (pluginExtension === void 0) { pluginExtension = null; }
  59422. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59423. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59424. return null;
  59425. }
  59426. if (SceneLoader.ShowLoadingScreen) {
  59427. scene.getEngine().displayLoadingUI();
  59428. }
  59429. var loadingToken = {};
  59430. scene._addPendingData(loadingToken);
  59431. var disposeHandler = function () {
  59432. scene._removePendingData(loadingToken);
  59433. scene.getEngine().hideLoadingUI();
  59434. };
  59435. var errorHandler = function (message, exception) {
  59436. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59437. if (onError) {
  59438. onError(scene, errorMessage, exception);
  59439. }
  59440. else {
  59441. BABYLON.Tools.Error(errorMessage);
  59442. // should the exception be thrown?
  59443. }
  59444. disposeHandler();
  59445. };
  59446. var progressHandler = onProgress ? function (event) {
  59447. try {
  59448. onProgress(event);
  59449. }
  59450. catch (e) {
  59451. errorHandler("Error in onProgress callback", e);
  59452. }
  59453. } : undefined;
  59454. var successHandler = function () {
  59455. if (onSuccess) {
  59456. try {
  59457. onSuccess(scene);
  59458. }
  59459. catch (e) {
  59460. errorHandler("Error in onSuccess callback", e);
  59461. }
  59462. }
  59463. scene._removePendingData(loadingToken);
  59464. };
  59465. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59466. if (sceneFilename === "") {
  59467. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59468. }
  59469. if (plugin.load) {
  59470. var syncedPlugin = plugin;
  59471. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59472. return;
  59473. }
  59474. scene.loadingPluginName = plugin.name;
  59475. successHandler();
  59476. }
  59477. else {
  59478. var asyncedPlugin = plugin;
  59479. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59480. scene.loadingPluginName = plugin.name;
  59481. successHandler();
  59482. }).catch(function (error) {
  59483. errorHandler(error.message, error);
  59484. });
  59485. }
  59486. if (SceneLoader.ShowLoadingScreen) {
  59487. scene.executeWhenReady(function () {
  59488. scene.getEngine().hideLoadingUI();
  59489. });
  59490. }
  59491. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59492. };
  59493. /**
  59494. * Append a scene
  59495. * @param rootUrl a string that defines the root url for scene and resources
  59496. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59497. * @param scene is the instance of BABYLON.Scene to append to
  59498. * @param onProgress a callback with a progress event for each file being loaded
  59499. * @param pluginExtension the extension used to determine the plugin
  59500. * @returns The given scene
  59501. */
  59502. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59503. if (onProgress === void 0) { onProgress = null; }
  59504. if (pluginExtension === void 0) { pluginExtension = null; }
  59505. return new Promise(function (resolve, reject) {
  59506. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59507. resolve(scene);
  59508. }, onProgress, function (scene, message, exception) {
  59509. reject(exception || new Error(message));
  59510. }, pluginExtension);
  59511. });
  59512. };
  59513. /**
  59514. * Load a scene into an asset container
  59515. * @param rootUrl a string that defines the root url for scene and resources
  59516. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59517. * @param scene is the instance of BABYLON.Scene to append to
  59518. * @param onSuccess a callback with the scene when import succeeds
  59519. * @param onProgress a callback with a progress event for each file being loaded
  59520. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59521. * @param pluginExtension the extension used to determine the plugin
  59522. * @returns The loaded plugin
  59523. */
  59524. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59525. if (onSuccess === void 0) { onSuccess = null; }
  59526. if (onProgress === void 0) { onProgress = null; }
  59527. if (onError === void 0) { onError = null; }
  59528. if (pluginExtension === void 0) { pluginExtension = null; }
  59529. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59530. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59531. return null;
  59532. }
  59533. var loadingToken = {};
  59534. scene._addPendingData(loadingToken);
  59535. var disposeHandler = function () {
  59536. scene._removePendingData(loadingToken);
  59537. };
  59538. var errorHandler = function (message, exception) {
  59539. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59540. if (onError) {
  59541. onError(scene, errorMessage, exception);
  59542. }
  59543. else {
  59544. BABYLON.Tools.Error(errorMessage);
  59545. // should the exception be thrown?
  59546. }
  59547. disposeHandler();
  59548. };
  59549. var progressHandler = onProgress ? function (event) {
  59550. try {
  59551. onProgress(event);
  59552. }
  59553. catch (e) {
  59554. errorHandler("Error in onProgress callback", e);
  59555. }
  59556. } : undefined;
  59557. var successHandler = function (assets) {
  59558. if (onSuccess) {
  59559. try {
  59560. onSuccess(assets);
  59561. }
  59562. catch (e) {
  59563. errorHandler("Error in onSuccess callback", e);
  59564. }
  59565. }
  59566. scene._removePendingData(loadingToken);
  59567. };
  59568. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59569. if (plugin.loadAssetContainer) {
  59570. var syncedPlugin = plugin;
  59571. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59572. if (!assetContainer) {
  59573. return;
  59574. }
  59575. scene.loadingPluginName = plugin.name;
  59576. successHandler(assetContainer);
  59577. }
  59578. else if (plugin.loadAssetContainerAsync) {
  59579. var asyncedPlugin = plugin;
  59580. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59581. scene.loadingPluginName = plugin.name;
  59582. successHandler(assetContainer);
  59583. }).catch(function (error) {
  59584. errorHandler(error.message, error);
  59585. });
  59586. }
  59587. else {
  59588. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59589. }
  59590. if (SceneLoader.ShowLoadingScreen) {
  59591. scene.executeWhenReady(function () {
  59592. scene.getEngine().hideLoadingUI();
  59593. });
  59594. }
  59595. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59596. };
  59597. /**
  59598. * Load a scene into an asset container
  59599. * @param rootUrl a string that defines the root url for scene and resources
  59600. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59601. * @param scene is the instance of BABYLON.Scene to append to
  59602. * @param onProgress a callback with a progress event for each file being loaded
  59603. * @param pluginExtension the extension used to determine the plugin
  59604. * @returns The loaded asset container
  59605. */
  59606. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59607. if (onProgress === void 0) { onProgress = null; }
  59608. if (pluginExtension === void 0) { pluginExtension = null; }
  59609. return new Promise(function (resolve, reject) {
  59610. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59611. resolve(assetContainer);
  59612. }, onProgress, function (scene, message, exception) {
  59613. reject(exception || new Error(message));
  59614. }, pluginExtension);
  59615. });
  59616. };
  59617. // Flags
  59618. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59619. SceneLoader._ShowLoadingScreen = true;
  59620. SceneLoader._CleanBoneMatrixWeights = false;
  59621. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59622. // Members
  59623. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59624. SceneLoader._registeredPlugins = {};
  59625. return SceneLoader;
  59626. }());
  59627. BABYLON.SceneLoader = SceneLoader;
  59628. ;
  59629. })(BABYLON || (BABYLON = {}));
  59630. //# sourceMappingURL=babylon.sceneLoader.js.map
  59631. var BABYLON;
  59632. (function (BABYLON) {
  59633. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59634. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59635. var parsedMaterial = parsedData.materials[index];
  59636. if (parsedMaterial.id === id) {
  59637. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59638. }
  59639. }
  59640. return null;
  59641. };
  59642. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59643. for (var i in names) {
  59644. if (mesh.name === names[i]) {
  59645. hierarchyIds.push(mesh.id);
  59646. return true;
  59647. }
  59648. }
  59649. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59650. hierarchyIds.push(mesh.id);
  59651. return true;
  59652. }
  59653. return false;
  59654. };
  59655. var logOperation = function (operation, producer) {
  59656. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59657. };
  59658. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59659. if (addToScene === void 0) { addToScene = false; }
  59660. var container = new BABYLON.AssetContainer(scene);
  59661. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59662. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59663. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59664. // and avoid problems with multiple concurrent .babylon loads.
  59665. var log = "importScene has failed JSON parse";
  59666. try {
  59667. var parsedData = JSON.parse(data);
  59668. log = "";
  59669. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59670. var index;
  59671. var cache;
  59672. // Lights
  59673. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59674. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59675. var parsedLight = parsedData.lights[index];
  59676. var light = BABYLON.Light.Parse(parsedLight, scene);
  59677. if (light) {
  59678. container.lights.push(light);
  59679. log += (index === 0 ? "\n\tLights:" : "");
  59680. log += "\n\t\t" + light.toString(fullDetails);
  59681. }
  59682. }
  59683. }
  59684. // Animations
  59685. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59686. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59687. var parsedAnimation = parsedData.animations[index];
  59688. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59689. scene.animations.push(animation);
  59690. container.animations.push(animation);
  59691. log += (index === 0 ? "\n\tAnimations:" : "");
  59692. log += "\n\t\t" + animation.toString(fullDetails);
  59693. }
  59694. }
  59695. // Materials
  59696. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59697. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59698. var parsedMaterial = parsedData.materials[index];
  59699. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59700. container.materials.push(mat);
  59701. log += (index === 0 ? "\n\tMaterials:" : "");
  59702. log += "\n\t\t" + mat.toString(fullDetails);
  59703. }
  59704. }
  59705. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59706. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59707. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59708. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59709. container.multiMaterials.push(mmat);
  59710. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59711. log += "\n\t\t" + mmat.toString(fullDetails);
  59712. }
  59713. }
  59714. // Morph targets
  59715. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59716. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59717. var managerData = _a[_i];
  59718. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59719. }
  59720. }
  59721. // Skeletons
  59722. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59723. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59724. var parsedSkeleton = parsedData.skeletons[index];
  59725. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59726. container.skeletons.push(skeleton);
  59727. log += (index === 0 ? "\n\tSkeletons:" : "");
  59728. log += "\n\t\t" + skeleton.toString(fullDetails);
  59729. }
  59730. }
  59731. // Geometries
  59732. var geometries = parsedData.geometries;
  59733. if (geometries !== undefined && geometries !== null) {
  59734. var addedGeometry = new Array();
  59735. // Boxes
  59736. var boxes = geometries.boxes;
  59737. if (boxes !== undefined && boxes !== null) {
  59738. for (index = 0, cache = boxes.length; index < cache; index++) {
  59739. var parsedBox = boxes[index];
  59740. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59741. }
  59742. }
  59743. // Spheres
  59744. var spheres = geometries.spheres;
  59745. if (spheres !== undefined && spheres !== null) {
  59746. for (index = 0, cache = spheres.length; index < cache; index++) {
  59747. var parsedSphere = spheres[index];
  59748. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59749. }
  59750. }
  59751. // Cylinders
  59752. var cylinders = geometries.cylinders;
  59753. if (cylinders !== undefined && cylinders !== null) {
  59754. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59755. var parsedCylinder = cylinders[index];
  59756. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59757. }
  59758. }
  59759. // Toruses
  59760. var toruses = geometries.toruses;
  59761. if (toruses !== undefined && toruses !== null) {
  59762. for (index = 0, cache = toruses.length; index < cache; index++) {
  59763. var parsedTorus = toruses[index];
  59764. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59765. }
  59766. }
  59767. // Grounds
  59768. var grounds = geometries.grounds;
  59769. if (grounds !== undefined && grounds !== null) {
  59770. for (index = 0, cache = grounds.length; index < cache; index++) {
  59771. var parsedGround = grounds[index];
  59772. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59773. }
  59774. }
  59775. // Planes
  59776. var planes = geometries.planes;
  59777. if (planes !== undefined && planes !== null) {
  59778. for (index = 0, cache = planes.length; index < cache; index++) {
  59779. var parsedPlane = planes[index];
  59780. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59781. }
  59782. }
  59783. // TorusKnots
  59784. var torusKnots = geometries.torusKnots;
  59785. if (torusKnots !== undefined && torusKnots !== null) {
  59786. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59787. var parsedTorusKnot = torusKnots[index];
  59788. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59789. }
  59790. }
  59791. // VertexData
  59792. var vertexData = geometries.vertexData;
  59793. if (vertexData !== undefined && vertexData !== null) {
  59794. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59795. var parsedVertexData = vertexData[index];
  59796. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59797. }
  59798. }
  59799. addedGeometry.forEach(function (g) {
  59800. if (g) {
  59801. container.geometries.push(g);
  59802. }
  59803. });
  59804. }
  59805. // Transform nodes
  59806. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59807. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59808. var parsedTransformNode = parsedData.transformNodes[index];
  59809. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59810. container.transformNodes.push(node);
  59811. }
  59812. }
  59813. // Meshes
  59814. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59815. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59816. var parsedMesh = parsedData.meshes[index];
  59817. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59818. container.meshes.push(mesh);
  59819. log += (index === 0 ? "\n\tMeshes:" : "");
  59820. log += "\n\t\t" + mesh.toString(fullDetails);
  59821. }
  59822. }
  59823. // Cameras
  59824. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59825. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59826. var parsedCamera = parsedData.cameras[index];
  59827. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59828. container.cameras.push(camera);
  59829. log += (index === 0 ? "\n\tCameras:" : "");
  59830. log += "\n\t\t" + camera.toString(fullDetails);
  59831. }
  59832. }
  59833. // Browsing all the graph to connect the dots
  59834. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59835. var camera = scene.cameras[index];
  59836. if (camera._waitingParentId) {
  59837. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59838. camera._waitingParentId = null;
  59839. }
  59840. }
  59841. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59842. var light_1 = scene.lights[index];
  59843. if (light_1 && light_1._waitingParentId) {
  59844. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59845. light_1._waitingParentId = null;
  59846. }
  59847. }
  59848. // Sounds
  59849. // TODO: add sound
  59850. var loadedSounds = [];
  59851. var loadedSound;
  59852. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59853. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59854. var parsedSound = parsedData.sounds[index];
  59855. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59856. if (!parsedSound.url)
  59857. parsedSound.url = parsedSound.name;
  59858. if (!loadedSounds[parsedSound.url]) {
  59859. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59860. loadedSounds[parsedSound.url] = loadedSound;
  59861. container.sounds.push(loadedSound);
  59862. }
  59863. else {
  59864. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59865. }
  59866. }
  59867. else {
  59868. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59869. }
  59870. }
  59871. }
  59872. loadedSounds = [];
  59873. // Connect parents & children and parse actions
  59874. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59875. var transformNode = scene.transformNodes[index];
  59876. if (transformNode._waitingParentId) {
  59877. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  59878. transformNode._waitingParentId = null;
  59879. }
  59880. }
  59881. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59882. var mesh = scene.meshes[index];
  59883. if (mesh._waitingParentId) {
  59884. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  59885. mesh._waitingParentId = null;
  59886. }
  59887. if (mesh._waitingActions) {
  59888. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  59889. mesh._waitingActions = null;
  59890. }
  59891. }
  59892. // freeze world matrix application
  59893. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59894. var currentMesh = scene.meshes[index];
  59895. if (currentMesh._waitingFreezeWorldMatrix) {
  59896. currentMesh.freezeWorldMatrix();
  59897. currentMesh._waitingFreezeWorldMatrix = null;
  59898. }
  59899. else {
  59900. currentMesh.computeWorldMatrix(true);
  59901. }
  59902. }
  59903. // Particles Systems
  59904. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59905. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59906. var parsedParticleSystem = parsedData.particleSystems[index];
  59907. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59908. container.particleSystems.push(ps);
  59909. }
  59910. }
  59911. // Lens flares
  59912. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  59913. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  59914. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  59915. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  59916. container.lensFlareSystems.push(lf);
  59917. }
  59918. }
  59919. // Shadows
  59920. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  59921. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  59922. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  59923. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  59924. container.shadowGenerators.push(sg);
  59925. }
  59926. }
  59927. // Lights exclusions / inclusions
  59928. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59929. var light_2 = scene.lights[index];
  59930. // Excluded check
  59931. if (light_2._excludedMeshesIds.length > 0) {
  59932. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  59933. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  59934. if (excludedMesh) {
  59935. light_2.excludedMeshes.push(excludedMesh);
  59936. }
  59937. }
  59938. light_2._excludedMeshesIds = [];
  59939. }
  59940. // Included check
  59941. if (light_2._includedOnlyMeshesIds.length > 0) {
  59942. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  59943. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  59944. if (includedOnlyMesh) {
  59945. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  59946. }
  59947. }
  59948. light_2._includedOnlyMeshesIds = [];
  59949. }
  59950. }
  59951. // Actions (scene)
  59952. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  59953. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  59954. }
  59955. if (!addToScene) {
  59956. container.removeAllFromScene();
  59957. }
  59958. }
  59959. catch (err) {
  59960. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  59961. if (onError) {
  59962. onError(msg, err);
  59963. }
  59964. else {
  59965. BABYLON.Tools.Log(msg);
  59966. throw err;
  59967. }
  59968. }
  59969. finally {
  59970. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59971. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59972. }
  59973. }
  59974. return container;
  59975. };
  59976. BABYLON.SceneLoader.RegisterPlugin({
  59977. name: "babylon.js",
  59978. extensions: ".babylon",
  59979. canDirectLoad: function (data) {
  59980. if (data.indexOf("babylon") !== -1) {
  59981. return true;
  59982. }
  59983. return false;
  59984. },
  59985. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  59986. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59987. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59988. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59989. // and avoid problems with multiple concurrent .babylon loads.
  59990. var log = "importMesh has failed JSON parse";
  59991. try {
  59992. var parsedData = JSON.parse(data);
  59993. log = "";
  59994. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59995. if (!meshesNames) {
  59996. meshesNames = null;
  59997. }
  59998. else if (!Array.isArray(meshesNames)) {
  59999. meshesNames = [meshesNames];
  60000. }
  60001. var hierarchyIds = new Array();
  60002. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60003. var loadedSkeletonsIds = [];
  60004. var loadedMaterialsIds = [];
  60005. var index;
  60006. var cache;
  60007. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60008. var parsedMesh = parsedData.meshes[index];
  60009. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60010. if (meshesNames !== null) {
  60011. // Remove found mesh name from list.
  60012. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60013. }
  60014. //Geometry?
  60015. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60016. //does the file contain geometries?
  60017. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60018. //find the correct geometry and add it to the scene
  60019. var found = false;
  60020. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60021. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60022. return;
  60023. }
  60024. else {
  60025. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60026. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60027. switch (geometryType) {
  60028. case "boxes":
  60029. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60030. break;
  60031. case "spheres":
  60032. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60033. break;
  60034. case "cylinders":
  60035. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60036. break;
  60037. case "toruses":
  60038. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60039. break;
  60040. case "grounds":
  60041. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60042. break;
  60043. case "planes":
  60044. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60045. break;
  60046. case "torusKnots":
  60047. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60048. break;
  60049. case "vertexData":
  60050. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60051. break;
  60052. }
  60053. found = true;
  60054. }
  60055. });
  60056. }
  60057. });
  60058. if (found === false) {
  60059. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60060. }
  60061. }
  60062. }
  60063. // Material ?
  60064. if (parsedMesh.materialId) {
  60065. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60066. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60067. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60068. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60069. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60070. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60071. var subMatId = parsedMultiMaterial.materials[matIndex];
  60072. loadedMaterialsIds.push(subMatId);
  60073. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60074. if (mat) {
  60075. log += "\n\tMaterial " + mat.toString(fullDetails);
  60076. }
  60077. }
  60078. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60079. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60080. if (mmat) {
  60081. materialFound = true;
  60082. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60083. }
  60084. break;
  60085. }
  60086. }
  60087. }
  60088. if (materialFound === false) {
  60089. loadedMaterialsIds.push(parsedMesh.materialId);
  60090. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60091. if (!mat) {
  60092. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60093. }
  60094. else {
  60095. log += "\n\tMaterial " + mat.toString(fullDetails);
  60096. }
  60097. }
  60098. }
  60099. // Skeleton ?
  60100. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60101. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60102. if (skeletonAlreadyLoaded === false) {
  60103. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60104. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60105. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60106. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60107. skeletons.push(skeleton);
  60108. loadedSkeletonsIds.push(parsedSkeleton.id);
  60109. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60110. }
  60111. }
  60112. }
  60113. }
  60114. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60115. meshes.push(mesh);
  60116. log += "\n\tMesh " + mesh.toString(fullDetails);
  60117. }
  60118. }
  60119. // Connecting parents
  60120. var currentMesh;
  60121. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60122. currentMesh = scene.meshes[index];
  60123. if (currentMesh._waitingParentId) {
  60124. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60125. currentMesh._waitingParentId = null;
  60126. }
  60127. }
  60128. // freeze and compute world matrix application
  60129. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60130. currentMesh = scene.meshes[index];
  60131. if (currentMesh._waitingFreezeWorldMatrix) {
  60132. currentMesh.freezeWorldMatrix();
  60133. currentMesh._waitingFreezeWorldMatrix = null;
  60134. }
  60135. else {
  60136. currentMesh.computeWorldMatrix(true);
  60137. }
  60138. }
  60139. }
  60140. // Particles
  60141. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60142. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60143. var parsedParticleSystem = parsedData.particleSystems[index];
  60144. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60145. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60146. }
  60147. }
  60148. }
  60149. return true;
  60150. }
  60151. catch (err) {
  60152. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60153. if (onError) {
  60154. onError(msg, err);
  60155. }
  60156. else {
  60157. BABYLON.Tools.Log(msg);
  60158. throw err;
  60159. }
  60160. }
  60161. finally {
  60162. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60163. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60164. }
  60165. }
  60166. return false;
  60167. },
  60168. load: function (scene, data, rootUrl, onError) {
  60169. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60170. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60171. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60172. // and avoid problems with multiple concurrent .babylon loads.
  60173. var log = "importScene has failed JSON parse";
  60174. try {
  60175. var parsedData = JSON.parse(data);
  60176. log = "";
  60177. // Scene
  60178. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60179. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60180. }
  60181. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60182. scene.autoClear = parsedData.autoClear;
  60183. }
  60184. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60185. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60186. }
  60187. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60188. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60189. }
  60190. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60191. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60192. }
  60193. // Fog
  60194. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60195. scene.fogMode = parsedData.fogMode;
  60196. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60197. scene.fogStart = parsedData.fogStart;
  60198. scene.fogEnd = parsedData.fogEnd;
  60199. scene.fogDensity = parsedData.fogDensity;
  60200. log += "\tFog mode for scene: ";
  60201. switch (scene.fogMode) {
  60202. // getters not compiling, so using hardcoded
  60203. case 1:
  60204. log += "exp\n";
  60205. break;
  60206. case 2:
  60207. log += "exp2\n";
  60208. break;
  60209. case 3:
  60210. log += "linear\n";
  60211. break;
  60212. }
  60213. }
  60214. //Physics
  60215. if (parsedData.physicsEnabled) {
  60216. var physicsPlugin;
  60217. if (parsedData.physicsEngine === "cannon") {
  60218. physicsPlugin = new BABYLON.CannonJSPlugin();
  60219. }
  60220. else if (parsedData.physicsEngine === "oimo") {
  60221. physicsPlugin = new BABYLON.OimoJSPlugin();
  60222. }
  60223. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60224. //else - default engine, which is currently oimo
  60225. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60226. scene.enablePhysics(physicsGravity, physicsPlugin);
  60227. }
  60228. // Metadata
  60229. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60230. scene.metadata = parsedData.metadata;
  60231. }
  60232. //collisions, if defined. otherwise, default is true
  60233. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60234. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60235. }
  60236. scene.workerCollisions = !!parsedData.workerCollisions;
  60237. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60238. if (!container) {
  60239. return false;
  60240. }
  60241. if (parsedData.autoAnimate) {
  60242. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60243. }
  60244. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60245. scene.setActiveCameraByID(parsedData.activeCameraID);
  60246. }
  60247. // Environment texture
  60248. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60249. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60250. if (parsedData.createDefaultSkybox === true) {
  60251. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60252. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60253. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60254. }
  60255. }
  60256. // Finish
  60257. return true;
  60258. }
  60259. catch (err) {
  60260. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60261. if (onError) {
  60262. onError(msg, err);
  60263. }
  60264. else {
  60265. BABYLON.Tools.Log(msg);
  60266. throw err;
  60267. }
  60268. }
  60269. finally {
  60270. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60271. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60272. }
  60273. }
  60274. return false;
  60275. },
  60276. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60277. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60278. return container;
  60279. }
  60280. });
  60281. })(BABYLON || (BABYLON = {}));
  60282. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60283. var BABYLON;
  60284. (function (BABYLON) {
  60285. var FilesInput = /** @class */ (function () {
  60286. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60287. this.onProcessFileCallback = function () { return true; };
  60288. this._engine = engine;
  60289. this._currentScene = scene;
  60290. this._sceneLoadedCallback = sceneLoadedCallback;
  60291. this._progressCallback = progressCallback;
  60292. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60293. this._textureLoadingCallback = textureLoadingCallback;
  60294. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60295. this._onReloadCallback = onReloadCallback;
  60296. this._errorCallback = errorCallback;
  60297. }
  60298. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60299. var _this = this;
  60300. if (elementToMonitor) {
  60301. this._elementToMonitor = elementToMonitor;
  60302. this._dragEnterHandler = function (e) { _this.drag(e); };
  60303. this._dragOverHandler = function (e) { _this.drag(e); };
  60304. this._dropHandler = function (e) { _this.drop(e); };
  60305. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60306. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60307. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60308. }
  60309. };
  60310. FilesInput.prototype.dispose = function () {
  60311. if (!this._elementToMonitor) {
  60312. return;
  60313. }
  60314. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60315. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60316. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60317. };
  60318. FilesInput.prototype.renderFunction = function () {
  60319. if (this._additionalRenderLoopLogicCallback) {
  60320. this._additionalRenderLoopLogicCallback();
  60321. }
  60322. if (this._currentScene) {
  60323. if (this._textureLoadingCallback) {
  60324. var remaining = this._currentScene.getWaitingItemsCount();
  60325. if (remaining > 0) {
  60326. this._textureLoadingCallback(remaining);
  60327. }
  60328. }
  60329. this._currentScene.render();
  60330. }
  60331. };
  60332. FilesInput.prototype.drag = function (e) {
  60333. e.stopPropagation();
  60334. e.preventDefault();
  60335. };
  60336. FilesInput.prototype.drop = function (eventDrop) {
  60337. eventDrop.stopPropagation();
  60338. eventDrop.preventDefault();
  60339. this.loadFiles(eventDrop);
  60340. };
  60341. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60342. var _this = this;
  60343. var reader = folder.createReader();
  60344. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60345. reader.readEntries(function (entries) {
  60346. remaining.count += entries.length;
  60347. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60348. var entry = entries_1[_i];
  60349. if (entry.isFile) {
  60350. entry.file(function (file) {
  60351. file.correctName = relativePath + file.name;
  60352. files.push(file);
  60353. if (--remaining.count === 0) {
  60354. callback();
  60355. }
  60356. });
  60357. }
  60358. else if (entry.isDirectory) {
  60359. _this._traverseFolder(entry, files, remaining, callback);
  60360. }
  60361. }
  60362. if (--remaining.count) {
  60363. callback();
  60364. }
  60365. });
  60366. };
  60367. FilesInput.prototype._processFiles = function (files) {
  60368. for (var i = 0; i < files.length; i++) {
  60369. var name = files[i].correctName.toLowerCase();
  60370. var extension = name.split('.').pop();
  60371. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60372. continue;
  60373. }
  60374. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60375. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60376. this._sceneFileToLoad = files[i];
  60377. }
  60378. else {
  60379. FilesInput.FilesToLoad[name] = files[i];
  60380. }
  60381. }
  60382. };
  60383. FilesInput.prototype.loadFiles = function (event) {
  60384. var _this = this;
  60385. if (this._startingProcessingFilesCallback)
  60386. this._startingProcessingFilesCallback();
  60387. // Handling data transfer via drag'n'drop
  60388. if (event && event.dataTransfer && event.dataTransfer.files) {
  60389. this._filesToLoad = event.dataTransfer.files;
  60390. }
  60391. // Handling files from input files
  60392. if (event && event.target && event.target.files) {
  60393. this._filesToLoad = event.target.files;
  60394. }
  60395. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60396. var files_1 = new Array();
  60397. var folders = [];
  60398. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60399. for (var i = 0; i < this._filesToLoad.length; i++) {
  60400. var fileToLoad = this._filesToLoad[i];
  60401. var name_1 = fileToLoad.name.toLowerCase();
  60402. var entry = void 0;
  60403. fileToLoad.correctName = name_1;
  60404. if (items) {
  60405. var item = items[i];
  60406. if (item.getAsEntry) {
  60407. entry = item.getAsEntry();
  60408. }
  60409. else if (item.webkitGetAsEntry) {
  60410. entry = item.webkitGetAsEntry();
  60411. }
  60412. }
  60413. if (!entry) {
  60414. files_1.push(fileToLoad);
  60415. }
  60416. else {
  60417. if (entry.isDirectory) {
  60418. folders.push(entry);
  60419. }
  60420. else {
  60421. files_1.push(fileToLoad);
  60422. }
  60423. }
  60424. }
  60425. if (folders.length === 0) {
  60426. this._processFiles(files_1);
  60427. this._processReload();
  60428. }
  60429. else {
  60430. var remaining = { count: folders.length };
  60431. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60432. var folder = folders_1[_i];
  60433. this._traverseFolder(folder, files_1, remaining, function () {
  60434. _this._processFiles(files_1);
  60435. if (remaining.count === 0) {
  60436. _this._processReload();
  60437. }
  60438. });
  60439. }
  60440. }
  60441. }
  60442. };
  60443. FilesInput.prototype._processReload = function () {
  60444. if (this._onReloadCallback) {
  60445. this._onReloadCallback(this._sceneFileToLoad);
  60446. }
  60447. else {
  60448. this.reload();
  60449. }
  60450. };
  60451. FilesInput.prototype.reload = function () {
  60452. var _this = this;
  60453. // If a scene file has been provided
  60454. if (this._sceneFileToLoad) {
  60455. if (this._currentScene) {
  60456. if (BABYLON.Tools.errorsCount > 0) {
  60457. BABYLON.Tools.ClearLogCache();
  60458. }
  60459. this._engine.stopRenderLoop();
  60460. this._currentScene.dispose();
  60461. }
  60462. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60463. if (_this._progressCallback) {
  60464. _this._progressCallback(progress);
  60465. }
  60466. }).then(function (scene) {
  60467. _this._currentScene = scene;
  60468. if (_this._sceneLoadedCallback) {
  60469. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60470. }
  60471. // Wait for textures and shaders to be ready
  60472. _this._currentScene.executeWhenReady(function () {
  60473. _this._engine.runRenderLoop(function () {
  60474. _this.renderFunction();
  60475. });
  60476. });
  60477. }).catch(function (error) {
  60478. if (_this._errorCallback) {
  60479. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60480. }
  60481. });
  60482. }
  60483. else {
  60484. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60485. }
  60486. };
  60487. FilesInput.FilesToLoad = {};
  60488. return FilesInput;
  60489. }());
  60490. BABYLON.FilesInput = FilesInput;
  60491. })(BABYLON || (BABYLON = {}));
  60492. //# sourceMappingURL=babylon.filesInput.js.map
  60493. var BABYLON;
  60494. (function (BABYLON) {
  60495. /**
  60496. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60497. * The underlying implementation relies on an associative array to ensure the best performances.
  60498. * The value can be anything including 'null' but except 'undefined'
  60499. */
  60500. var StringDictionary = /** @class */ (function () {
  60501. function StringDictionary() {
  60502. this._count = 0;
  60503. this._data = {};
  60504. }
  60505. /**
  60506. * This will clear this dictionary and copy the content from the 'source' one.
  60507. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60508. * @param source the dictionary to take the content from and copy to this dictionary
  60509. */
  60510. StringDictionary.prototype.copyFrom = function (source) {
  60511. var _this = this;
  60512. this.clear();
  60513. source.forEach(function (t, v) { return _this.add(t, v); });
  60514. };
  60515. /**
  60516. * Get a value based from its key
  60517. * @param key the given key to get the matching value from
  60518. * @return the value if found, otherwise undefined is returned
  60519. */
  60520. StringDictionary.prototype.get = function (key) {
  60521. var val = this._data[key];
  60522. if (val !== undefined) {
  60523. return val;
  60524. }
  60525. return undefined;
  60526. };
  60527. /**
  60528. * Get a value from its key or add it if it doesn't exist.
  60529. * This method will ensure you that a given key/data will be present in the dictionary.
  60530. * @param key the given key to get the matching value from
  60531. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60532. * The factory will only be invoked if there's no data for the given key.
  60533. * @return the value corresponding to the key.
  60534. */
  60535. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60536. var val = this.get(key);
  60537. if (val !== undefined) {
  60538. return val;
  60539. }
  60540. val = factory(key);
  60541. if (val) {
  60542. this.add(key, val);
  60543. }
  60544. return val;
  60545. };
  60546. /**
  60547. * Get a value from its key if present in the dictionary otherwise add it
  60548. * @param key the key to get the value from
  60549. * @param val if there's no such key/value pair in the dictionary add it with this value
  60550. * @return the value corresponding to the key
  60551. */
  60552. StringDictionary.prototype.getOrAdd = function (key, val) {
  60553. var curVal = this.get(key);
  60554. if (curVal !== undefined) {
  60555. return curVal;
  60556. }
  60557. this.add(key, val);
  60558. return val;
  60559. };
  60560. /**
  60561. * Check if there's a given key in the dictionary
  60562. * @param key the key to check for
  60563. * @return true if the key is present, false otherwise
  60564. */
  60565. StringDictionary.prototype.contains = function (key) {
  60566. return this._data[key] !== undefined;
  60567. };
  60568. /**
  60569. * Add a new key and its corresponding value
  60570. * @param key the key to add
  60571. * @param value the value corresponding to the key
  60572. * @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
  60573. */
  60574. StringDictionary.prototype.add = function (key, value) {
  60575. if (this._data[key] !== undefined) {
  60576. return false;
  60577. }
  60578. this._data[key] = value;
  60579. ++this._count;
  60580. return true;
  60581. };
  60582. StringDictionary.prototype.set = function (key, value) {
  60583. if (this._data[key] === undefined) {
  60584. return false;
  60585. }
  60586. this._data[key] = value;
  60587. return true;
  60588. };
  60589. /**
  60590. * Get the element of the given key and remove it from the dictionary
  60591. * @param key
  60592. */
  60593. StringDictionary.prototype.getAndRemove = function (key) {
  60594. var val = this.get(key);
  60595. if (val !== undefined) {
  60596. delete this._data[key];
  60597. --this._count;
  60598. return val;
  60599. }
  60600. return null;
  60601. };
  60602. /**
  60603. * Remove a key/value from the dictionary.
  60604. * @param key the key to remove
  60605. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60606. */
  60607. StringDictionary.prototype.remove = function (key) {
  60608. if (this.contains(key)) {
  60609. delete this._data[key];
  60610. --this._count;
  60611. return true;
  60612. }
  60613. return false;
  60614. };
  60615. /**
  60616. * Clear the whole content of the dictionary
  60617. */
  60618. StringDictionary.prototype.clear = function () {
  60619. this._data = {};
  60620. this._count = 0;
  60621. };
  60622. Object.defineProperty(StringDictionary.prototype, "count", {
  60623. get: function () {
  60624. return this._count;
  60625. },
  60626. enumerable: true,
  60627. configurable: true
  60628. });
  60629. /**
  60630. * Execute a callback on each key/val of the dictionary.
  60631. * Note that you can remove any element in this dictionary in the callback implementation
  60632. * @param callback the callback to execute on a given key/value pair
  60633. */
  60634. StringDictionary.prototype.forEach = function (callback) {
  60635. for (var cur in this._data) {
  60636. var val = this._data[cur];
  60637. callback(cur, val);
  60638. }
  60639. };
  60640. /**
  60641. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60642. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60643. * Note that you can remove any element in this dictionary in the callback implementation
  60644. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60645. */
  60646. StringDictionary.prototype.first = function (callback) {
  60647. for (var cur in this._data) {
  60648. var val = this._data[cur];
  60649. var res = callback(cur, val);
  60650. if (res) {
  60651. return res;
  60652. }
  60653. }
  60654. return null;
  60655. };
  60656. return StringDictionary;
  60657. }());
  60658. BABYLON.StringDictionary = StringDictionary;
  60659. })(BABYLON || (BABYLON = {}));
  60660. //# sourceMappingURL=babylon.stringDictionary.js.map
  60661. var BABYLON;
  60662. (function (BABYLON) {
  60663. var Tags = /** @class */ (function () {
  60664. function Tags() {
  60665. }
  60666. Tags.EnableFor = function (obj) {
  60667. obj._tags = obj._tags || {};
  60668. obj.hasTags = function () {
  60669. return Tags.HasTags(obj);
  60670. };
  60671. obj.addTags = function (tagsString) {
  60672. return Tags.AddTagsTo(obj, tagsString);
  60673. };
  60674. obj.removeTags = function (tagsString) {
  60675. return Tags.RemoveTagsFrom(obj, tagsString);
  60676. };
  60677. obj.matchesTagsQuery = function (tagsQuery) {
  60678. return Tags.MatchesQuery(obj, tagsQuery);
  60679. };
  60680. };
  60681. Tags.DisableFor = function (obj) {
  60682. delete obj._tags;
  60683. delete obj.hasTags;
  60684. delete obj.addTags;
  60685. delete obj.removeTags;
  60686. delete obj.matchesTagsQuery;
  60687. };
  60688. Tags.HasTags = function (obj) {
  60689. if (!obj._tags) {
  60690. return false;
  60691. }
  60692. return !BABYLON.Tools.IsEmpty(obj._tags);
  60693. };
  60694. Tags.GetTags = function (obj, asString) {
  60695. if (asString === void 0) { asString = true; }
  60696. if (!obj._tags) {
  60697. return null;
  60698. }
  60699. if (asString) {
  60700. var tagsArray = [];
  60701. for (var tag in obj._tags) {
  60702. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60703. tagsArray.push(tag);
  60704. }
  60705. }
  60706. return tagsArray.join(" ");
  60707. }
  60708. else {
  60709. return obj._tags;
  60710. }
  60711. };
  60712. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60713. // a tag cannot start with '||', '&&', and '!'
  60714. // it cannot contain whitespaces
  60715. Tags.AddTagsTo = function (obj, tagsString) {
  60716. if (!tagsString) {
  60717. return;
  60718. }
  60719. if (typeof tagsString !== "string") {
  60720. return;
  60721. }
  60722. var tags = tagsString.split(" ");
  60723. tags.forEach(function (tag, index, array) {
  60724. Tags._AddTagTo(obj, tag);
  60725. });
  60726. };
  60727. Tags._AddTagTo = function (obj, tag) {
  60728. tag = tag.trim();
  60729. if (tag === "" || tag === "true" || tag === "false") {
  60730. return;
  60731. }
  60732. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60733. return;
  60734. }
  60735. Tags.EnableFor(obj);
  60736. obj._tags[tag] = true;
  60737. };
  60738. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60739. if (!Tags.HasTags(obj)) {
  60740. return;
  60741. }
  60742. var tags = tagsString.split(" ");
  60743. for (var t in tags) {
  60744. Tags._RemoveTagFrom(obj, tags[t]);
  60745. }
  60746. };
  60747. Tags._RemoveTagFrom = function (obj, tag) {
  60748. delete obj._tags[tag];
  60749. };
  60750. Tags.MatchesQuery = function (obj, tagsQuery) {
  60751. if (tagsQuery === undefined) {
  60752. return true;
  60753. }
  60754. if (tagsQuery === "") {
  60755. return Tags.HasTags(obj);
  60756. }
  60757. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60758. };
  60759. return Tags;
  60760. }());
  60761. BABYLON.Tags = Tags;
  60762. })(BABYLON || (BABYLON = {}));
  60763. //# sourceMappingURL=babylon.tags.js.map
  60764. var BABYLON;
  60765. (function (BABYLON) {
  60766. var AndOrNotEvaluator = /** @class */ (function () {
  60767. function AndOrNotEvaluator() {
  60768. }
  60769. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60770. if (!query.match(/\([^\(\)]*\)/g)) {
  60771. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60772. }
  60773. else {
  60774. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60775. // remove parenthesis
  60776. r = r.slice(1, r.length - 1);
  60777. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60778. });
  60779. }
  60780. if (query === "true") {
  60781. return true;
  60782. }
  60783. if (query === "false") {
  60784. return false;
  60785. }
  60786. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60787. };
  60788. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60789. evaluateCallback = evaluateCallback || (function (r) {
  60790. return r === "true" ? true : false;
  60791. });
  60792. var result;
  60793. var or = parenthesisContent.split("||");
  60794. for (var i in or) {
  60795. if (or.hasOwnProperty(i)) {
  60796. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60797. var and = ori.split("&&");
  60798. if (and.length > 1) {
  60799. for (var j = 0; j < and.length; ++j) {
  60800. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60801. if (andj !== "true" && andj !== "false") {
  60802. if (andj[0] === "!") {
  60803. result = !evaluateCallback(andj.substring(1));
  60804. }
  60805. else {
  60806. result = evaluateCallback(andj);
  60807. }
  60808. }
  60809. else {
  60810. result = andj === "true" ? true : false;
  60811. }
  60812. if (!result) {
  60813. ori = "false";
  60814. break;
  60815. }
  60816. }
  60817. }
  60818. if (result || ori === "true") {
  60819. result = true;
  60820. break;
  60821. }
  60822. // result equals false (or undefined)
  60823. if (ori !== "true" && ori !== "false") {
  60824. if (ori[0] === "!") {
  60825. result = !evaluateCallback(ori.substring(1));
  60826. }
  60827. else {
  60828. result = evaluateCallback(ori);
  60829. }
  60830. }
  60831. else {
  60832. result = ori === "true" ? true : false;
  60833. }
  60834. }
  60835. }
  60836. // the whole parenthesis scope is replaced by 'true' or 'false'
  60837. return result ? "true" : "false";
  60838. };
  60839. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60840. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60841. // remove whitespaces
  60842. r = r.replace(/[\s]/g, function () { return ""; });
  60843. return r.length % 2 ? "!" : "";
  60844. });
  60845. booleanString = booleanString.trim();
  60846. if (booleanString === "!true") {
  60847. booleanString = "false";
  60848. }
  60849. else if (booleanString === "!false") {
  60850. booleanString = "true";
  60851. }
  60852. return booleanString;
  60853. };
  60854. return AndOrNotEvaluator;
  60855. }());
  60856. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60857. })(BABYLON || (BABYLON = {}));
  60858. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60859. var BABYLON;
  60860. (function (BABYLON) {
  60861. var Database = /** @class */ (function () {
  60862. function Database(urlToScene, callbackManifestChecked) {
  60863. // Handling various flavors of prefixed version of IndexedDB
  60864. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60865. this.callbackManifestChecked = callbackManifestChecked;
  60866. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60867. this.db = null;
  60868. this._enableSceneOffline = false;
  60869. this._enableTexturesOffline = false;
  60870. this.manifestVersionFound = 0;
  60871. this.mustUpdateRessources = false;
  60872. this.hasReachedQuota = false;
  60873. if (!Database.IDBStorageEnabled) {
  60874. this.callbackManifestChecked(true);
  60875. }
  60876. else {
  60877. this.checkManifestFile();
  60878. }
  60879. }
  60880. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  60881. get: function () {
  60882. return this._enableSceneOffline;
  60883. },
  60884. enumerable: true,
  60885. configurable: true
  60886. });
  60887. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  60888. get: function () {
  60889. return this._enableTexturesOffline;
  60890. },
  60891. enumerable: true,
  60892. configurable: true
  60893. });
  60894. Database.prototype.checkManifestFile = function () {
  60895. var _this = this;
  60896. var noManifestFile = function () {
  60897. _this._enableSceneOffline = false;
  60898. _this._enableTexturesOffline = false;
  60899. _this.callbackManifestChecked(false);
  60900. };
  60901. var timeStampUsed = false;
  60902. var manifestURL = this.currentSceneUrl + ".manifest";
  60903. var xhr = new XMLHttpRequest();
  60904. if (navigator.onLine) {
  60905. // Adding a timestamp to by-pass browsers' cache
  60906. timeStampUsed = true;
  60907. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  60908. }
  60909. xhr.open("GET", manifestURL, true);
  60910. xhr.addEventListener("load", function () {
  60911. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60912. try {
  60913. var manifestFile = JSON.parse(xhr.response);
  60914. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  60915. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  60916. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  60917. _this.manifestVersionFound = manifestFile.version;
  60918. }
  60919. if (_this.callbackManifestChecked) {
  60920. _this.callbackManifestChecked(true);
  60921. }
  60922. }
  60923. catch (ex) {
  60924. noManifestFile();
  60925. }
  60926. }
  60927. else {
  60928. noManifestFile();
  60929. }
  60930. }, false);
  60931. xhr.addEventListener("error", function (event) {
  60932. if (timeStampUsed) {
  60933. timeStampUsed = false;
  60934. // Let's retry without the timeStamp
  60935. // It could fail when coupled with HTML5 Offline API
  60936. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  60937. xhr.open("GET", retryManifestURL, true);
  60938. xhr.send();
  60939. }
  60940. else {
  60941. noManifestFile();
  60942. }
  60943. }, false);
  60944. try {
  60945. xhr.send();
  60946. }
  60947. catch (ex) {
  60948. BABYLON.Tools.Error("Error on XHR send request.");
  60949. this.callbackManifestChecked(false);
  60950. }
  60951. };
  60952. Database.prototype.openAsync = function (successCallback, errorCallback) {
  60953. var _this = this;
  60954. var handleError = function () {
  60955. _this.isSupported = false;
  60956. if (errorCallback)
  60957. errorCallback();
  60958. };
  60959. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  60960. // Your browser doesn't support IndexedDB
  60961. this.isSupported = false;
  60962. if (errorCallback)
  60963. errorCallback();
  60964. }
  60965. else {
  60966. // If the DB hasn't been opened or created yet
  60967. if (!this.db) {
  60968. this.hasReachedQuota = false;
  60969. this.isSupported = true;
  60970. var request = this.idbFactory.open("babylonjs", 1);
  60971. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  60972. request.onerror = function (event) {
  60973. handleError();
  60974. };
  60975. // executes when a version change transaction cannot complete due to other active transactions
  60976. request.onblocked = function (event) {
  60977. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  60978. handleError();
  60979. };
  60980. // DB has been opened successfully
  60981. request.onsuccess = function (event) {
  60982. _this.db = request.result;
  60983. successCallback();
  60984. };
  60985. // Initialization of the DB. Creating Scenes & Textures stores
  60986. request.onupgradeneeded = function (event) {
  60987. _this.db = (event.target).result;
  60988. if (_this.db) {
  60989. try {
  60990. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  60991. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  60992. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  60993. }
  60994. catch (ex) {
  60995. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  60996. handleError();
  60997. }
  60998. }
  60999. };
  61000. }
  61001. else {
  61002. if (successCallback)
  61003. successCallback();
  61004. }
  61005. }
  61006. };
  61007. Database.prototype.loadImageFromDB = function (url, image) {
  61008. var _this = this;
  61009. var completeURL = Database.ReturnFullUrlLocation(url);
  61010. var saveAndLoadImage = function () {
  61011. if (!_this.hasReachedQuota && _this.db !== null) {
  61012. // the texture is not yet in the DB, let's try to save it
  61013. _this._saveImageIntoDBAsync(completeURL, image);
  61014. }
  61015. else {
  61016. image.src = url;
  61017. }
  61018. };
  61019. if (!this.mustUpdateRessources) {
  61020. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61021. }
  61022. else {
  61023. saveAndLoadImage();
  61024. }
  61025. };
  61026. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61027. if (this.isSupported && this.db !== null) {
  61028. var texture;
  61029. var transaction = this.db.transaction(["textures"]);
  61030. transaction.onabort = function (event) {
  61031. image.src = url;
  61032. };
  61033. transaction.oncomplete = function (event) {
  61034. var blobTextureURL;
  61035. if (texture) {
  61036. var URL = window.URL || window.webkitURL;
  61037. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61038. image.onerror = function () {
  61039. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61040. image.src = url;
  61041. };
  61042. image.src = blobTextureURL;
  61043. }
  61044. else {
  61045. notInDBCallback();
  61046. }
  61047. };
  61048. var getRequest = transaction.objectStore("textures").get(url);
  61049. getRequest.onsuccess = function (event) {
  61050. texture = (event.target).result;
  61051. };
  61052. getRequest.onerror = function (event) {
  61053. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61054. image.src = url;
  61055. };
  61056. }
  61057. else {
  61058. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61059. image.src = url;
  61060. }
  61061. };
  61062. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61063. var _this = this;
  61064. if (this.isSupported) {
  61065. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61066. var generateBlobUrl = function () {
  61067. var blobTextureURL;
  61068. if (blob) {
  61069. var URL = window.URL || window.webkitURL;
  61070. try {
  61071. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61072. }
  61073. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61074. catch (ex) {
  61075. blobTextureURL = URL.createObjectURL(blob);
  61076. }
  61077. }
  61078. if (blobTextureURL) {
  61079. image.src = blobTextureURL;
  61080. }
  61081. };
  61082. if (Database.IsUASupportingBlobStorage) {
  61083. var xhr = new XMLHttpRequest(), blob;
  61084. xhr.open("GET", url, true);
  61085. xhr.responseType = "blob";
  61086. xhr.addEventListener("load", function () {
  61087. if (xhr.status === 200 && _this.db) {
  61088. // Blob as response (XHR2)
  61089. blob = xhr.response;
  61090. var transaction = _this.db.transaction(["textures"], "readwrite");
  61091. // the transaction could abort because of a QuotaExceededError error
  61092. transaction.onabort = function (event) {
  61093. try {
  61094. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61095. var srcElement = (event.srcElement || event.target);
  61096. var error = srcElement.error;
  61097. if (error && error.name === "QuotaExceededError") {
  61098. _this.hasReachedQuota = true;
  61099. }
  61100. }
  61101. catch (ex) { }
  61102. generateBlobUrl();
  61103. };
  61104. transaction.oncomplete = function (event) {
  61105. generateBlobUrl();
  61106. };
  61107. var newTexture = { textureUrl: url, data: blob };
  61108. try {
  61109. // Put the blob into the dabase
  61110. var addRequest = transaction.objectStore("textures").put(newTexture);
  61111. addRequest.onsuccess = function (event) {
  61112. };
  61113. addRequest.onerror = function (event) {
  61114. generateBlobUrl();
  61115. };
  61116. }
  61117. catch (ex) {
  61118. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61119. if (ex.code === 25) {
  61120. Database.IsUASupportingBlobStorage = false;
  61121. }
  61122. image.src = url;
  61123. }
  61124. }
  61125. else {
  61126. image.src = url;
  61127. }
  61128. }, false);
  61129. xhr.addEventListener("error", function (event) {
  61130. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61131. image.src = url;
  61132. }, false);
  61133. xhr.send();
  61134. }
  61135. else {
  61136. image.src = url;
  61137. }
  61138. }
  61139. else {
  61140. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61141. image.src = url;
  61142. }
  61143. };
  61144. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61145. var _this = this;
  61146. var updateVersion = function () {
  61147. // the version is not yet in the DB or we need to update it
  61148. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61149. };
  61150. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61151. };
  61152. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61153. var _this = this;
  61154. if (this.isSupported && this.db) {
  61155. var version;
  61156. try {
  61157. var transaction = this.db.transaction(["versions"]);
  61158. transaction.oncomplete = function (event) {
  61159. if (version) {
  61160. // If the version in the JSON file is > than the version in DB
  61161. if (_this.manifestVersionFound > version.data) {
  61162. _this.mustUpdateRessources = true;
  61163. updateInDBCallback();
  61164. }
  61165. else {
  61166. callback(version.data);
  61167. }
  61168. }
  61169. else {
  61170. _this.mustUpdateRessources = true;
  61171. updateInDBCallback();
  61172. }
  61173. };
  61174. transaction.onabort = function (event) {
  61175. callback(-1);
  61176. };
  61177. var getRequest = transaction.objectStore("versions").get(url);
  61178. getRequest.onsuccess = function (event) {
  61179. version = (event.target).result;
  61180. };
  61181. getRequest.onerror = function (event) {
  61182. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61183. callback(-1);
  61184. };
  61185. }
  61186. catch (ex) {
  61187. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61188. callback(-1);
  61189. }
  61190. }
  61191. else {
  61192. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61193. callback(-1);
  61194. }
  61195. };
  61196. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61197. var _this = this;
  61198. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61199. try {
  61200. // Open a transaction to the database
  61201. var transaction = this.db.transaction(["versions"], "readwrite");
  61202. // the transaction could abort because of a QuotaExceededError error
  61203. transaction.onabort = function (event) {
  61204. try {
  61205. var error = event.srcElement['error'];
  61206. if (error && error.name === "QuotaExceededError") {
  61207. _this.hasReachedQuota = true;
  61208. }
  61209. }
  61210. catch (ex) { }
  61211. callback(-1);
  61212. };
  61213. transaction.oncomplete = function (event) {
  61214. callback(_this.manifestVersionFound);
  61215. };
  61216. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61217. // Put the scene into the database
  61218. var addRequest = transaction.objectStore("versions").put(newVersion);
  61219. addRequest.onsuccess = function (event) {
  61220. };
  61221. addRequest.onerror = function (event) {
  61222. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61223. };
  61224. }
  61225. catch (ex) {
  61226. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61227. callback(-1);
  61228. }
  61229. }
  61230. else {
  61231. callback(-1);
  61232. }
  61233. };
  61234. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61235. var _this = this;
  61236. var completeUrl = Database.ReturnFullUrlLocation(url);
  61237. var saveAndLoadFile = function () {
  61238. // the scene is not yet in the DB, let's try to save it
  61239. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61240. };
  61241. this._checkVersionFromDB(completeUrl, function (version) {
  61242. if (version !== -1) {
  61243. if (!_this.mustUpdateRessources) {
  61244. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61245. }
  61246. else {
  61247. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61248. }
  61249. }
  61250. else {
  61251. if (errorCallback) {
  61252. errorCallback();
  61253. }
  61254. }
  61255. });
  61256. };
  61257. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61258. if (this.isSupported && this.db) {
  61259. var targetStore;
  61260. if (url.indexOf(".babylon") !== -1) {
  61261. targetStore = "scenes";
  61262. }
  61263. else {
  61264. targetStore = "textures";
  61265. }
  61266. var file;
  61267. var transaction = this.db.transaction([targetStore]);
  61268. transaction.oncomplete = function (event) {
  61269. if (file) {
  61270. callback(file.data);
  61271. }
  61272. else {
  61273. notInDBCallback();
  61274. }
  61275. };
  61276. transaction.onabort = function (event) {
  61277. notInDBCallback();
  61278. };
  61279. var getRequest = transaction.objectStore(targetStore).get(url);
  61280. getRequest.onsuccess = function (event) {
  61281. file = (event.target).result;
  61282. };
  61283. getRequest.onerror = function (event) {
  61284. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61285. notInDBCallback();
  61286. };
  61287. }
  61288. else {
  61289. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61290. callback();
  61291. }
  61292. };
  61293. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61294. var _this = this;
  61295. if (this.isSupported) {
  61296. var targetStore;
  61297. if (url.indexOf(".babylon") !== -1) {
  61298. targetStore = "scenes";
  61299. }
  61300. else {
  61301. targetStore = "textures";
  61302. }
  61303. // Create XHR
  61304. var xhr = new XMLHttpRequest();
  61305. var fileData;
  61306. xhr.open("GET", url, true);
  61307. if (useArrayBuffer) {
  61308. xhr.responseType = "arraybuffer";
  61309. }
  61310. if (progressCallback) {
  61311. xhr.onprogress = progressCallback;
  61312. }
  61313. xhr.addEventListener("load", function () {
  61314. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61315. // Blob as response (XHR2)
  61316. //fileData = xhr.responseText;
  61317. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61318. if (!_this.hasReachedQuota && _this.db) {
  61319. // Open a transaction to the database
  61320. var transaction = _this.db.transaction([targetStore], "readwrite");
  61321. // the transaction could abort because of a QuotaExceededError error
  61322. transaction.onabort = function (event) {
  61323. try {
  61324. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61325. var error = event.srcElement['error'];
  61326. if (error && error.name === "QuotaExceededError") {
  61327. _this.hasReachedQuota = true;
  61328. }
  61329. }
  61330. catch (ex) { }
  61331. callback(fileData);
  61332. };
  61333. transaction.oncomplete = function (event) {
  61334. callback(fileData);
  61335. };
  61336. var newFile;
  61337. if (targetStore === "scenes") {
  61338. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61339. }
  61340. else {
  61341. newFile = { textureUrl: url, data: fileData };
  61342. }
  61343. try {
  61344. // Put the scene into the database
  61345. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61346. addRequest.onsuccess = function (event) {
  61347. };
  61348. addRequest.onerror = function (event) {
  61349. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61350. };
  61351. }
  61352. catch (ex) {
  61353. callback(fileData);
  61354. }
  61355. }
  61356. else {
  61357. callback(fileData);
  61358. }
  61359. }
  61360. else {
  61361. callback();
  61362. }
  61363. }, false);
  61364. xhr.addEventListener("error", function (event) {
  61365. BABYLON.Tools.Error("error on XHR request.");
  61366. callback();
  61367. }, false);
  61368. xhr.send();
  61369. }
  61370. else {
  61371. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61372. callback();
  61373. }
  61374. };
  61375. Database.IsUASupportingBlobStorage = true;
  61376. Database.IDBStorageEnabled = true;
  61377. Database.parseURL = function (url) {
  61378. var a = document.createElement('a');
  61379. a.href = url;
  61380. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61381. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61382. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61383. return absLocation;
  61384. };
  61385. Database.ReturnFullUrlLocation = function (url) {
  61386. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61387. return (Database.parseURL(window.location.href) + url);
  61388. }
  61389. else {
  61390. return url;
  61391. }
  61392. };
  61393. return Database;
  61394. }());
  61395. BABYLON.Database = Database;
  61396. })(BABYLON || (BABYLON = {}));
  61397. //# sourceMappingURL=babylon.database.js.map
  61398. var BABYLON;
  61399. (function (BABYLON) {
  61400. var FresnelParameters = /** @class */ (function () {
  61401. function FresnelParameters() {
  61402. this._isEnabled = true;
  61403. this.leftColor = BABYLON.Color3.White();
  61404. this.rightColor = BABYLON.Color3.Black();
  61405. this.bias = 0;
  61406. this.power = 1;
  61407. }
  61408. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61409. get: function () {
  61410. return this._isEnabled;
  61411. },
  61412. set: function (value) {
  61413. if (this._isEnabled === value) {
  61414. return;
  61415. }
  61416. this._isEnabled = value;
  61417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61418. },
  61419. enumerable: true,
  61420. configurable: true
  61421. });
  61422. FresnelParameters.prototype.clone = function () {
  61423. var newFresnelParameters = new FresnelParameters();
  61424. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61425. return newFresnelParameters;
  61426. };
  61427. FresnelParameters.prototype.serialize = function () {
  61428. var serializationObject = {};
  61429. serializationObject.isEnabled = this.isEnabled;
  61430. serializationObject.leftColor = this.leftColor;
  61431. serializationObject.rightColor = this.rightColor;
  61432. serializationObject.bias = this.bias;
  61433. serializationObject.power = this.power;
  61434. return serializationObject;
  61435. };
  61436. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61437. var fresnelParameters = new FresnelParameters();
  61438. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61439. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61440. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61441. fresnelParameters.bias = parsedFresnelParameters.bias;
  61442. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61443. return fresnelParameters;
  61444. };
  61445. return FresnelParameters;
  61446. }());
  61447. BABYLON.FresnelParameters = FresnelParameters;
  61448. })(BABYLON || (BABYLON = {}));
  61449. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61450. var BABYLON;
  61451. (function (BABYLON) {
  61452. var MultiMaterial = /** @class */ (function (_super) {
  61453. __extends(MultiMaterial, _super);
  61454. function MultiMaterial(name, scene) {
  61455. var _this = _super.call(this, name, scene, true) || this;
  61456. scene.multiMaterials.push(_this);
  61457. _this.subMaterials = new Array();
  61458. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61459. return _this;
  61460. }
  61461. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61462. get: function () {
  61463. return this._subMaterials;
  61464. },
  61465. set: function (value) {
  61466. this._subMaterials = value;
  61467. this._hookArray(value);
  61468. },
  61469. enumerable: true,
  61470. configurable: true
  61471. });
  61472. MultiMaterial.prototype._hookArray = function (array) {
  61473. var _this = this;
  61474. var oldPush = array.push;
  61475. array.push = function () {
  61476. var items = [];
  61477. for (var _i = 0; _i < arguments.length; _i++) {
  61478. items[_i] = arguments[_i];
  61479. }
  61480. var result = oldPush.apply(array, items);
  61481. _this._markAllSubMeshesAsTexturesDirty();
  61482. return result;
  61483. };
  61484. var oldSplice = array.splice;
  61485. array.splice = function (index, deleteCount) {
  61486. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61487. _this._markAllSubMeshesAsTexturesDirty();
  61488. return deleted;
  61489. };
  61490. };
  61491. // Properties
  61492. MultiMaterial.prototype.getSubMaterial = function (index) {
  61493. if (index < 0 || index >= this.subMaterials.length) {
  61494. return this.getScene().defaultMaterial;
  61495. }
  61496. return this.subMaterials[index];
  61497. };
  61498. MultiMaterial.prototype.getActiveTextures = function () {
  61499. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61500. if (subMaterial) {
  61501. return subMaterial.getActiveTextures();
  61502. }
  61503. else {
  61504. return [];
  61505. }
  61506. }));
  61507. var _a;
  61508. };
  61509. // Methods
  61510. MultiMaterial.prototype.getClassName = function () {
  61511. return "MultiMaterial";
  61512. };
  61513. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61514. for (var index = 0; index < this.subMaterials.length; index++) {
  61515. var subMaterial = this.subMaterials[index];
  61516. if (subMaterial) {
  61517. if (subMaterial.storeEffectOnSubMeshes) {
  61518. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61519. return false;
  61520. }
  61521. continue;
  61522. }
  61523. if (!subMaterial.isReady(mesh)) {
  61524. return false;
  61525. }
  61526. }
  61527. }
  61528. return true;
  61529. };
  61530. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61531. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61532. for (var index = 0; index < this.subMaterials.length; index++) {
  61533. var subMaterial = null;
  61534. var current = this.subMaterials[index];
  61535. if (cloneChildren && current) {
  61536. subMaterial = current.clone(name + "-" + current.name);
  61537. }
  61538. else {
  61539. subMaterial = this.subMaterials[index];
  61540. }
  61541. newMultiMaterial.subMaterials.push(subMaterial);
  61542. }
  61543. return newMultiMaterial;
  61544. };
  61545. MultiMaterial.prototype.serialize = function () {
  61546. var serializationObject = {};
  61547. serializationObject.name = this.name;
  61548. serializationObject.id = this.id;
  61549. if (BABYLON.Tags) {
  61550. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61551. }
  61552. serializationObject.materials = [];
  61553. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61554. var subMat = this.subMaterials[matIndex];
  61555. if (subMat) {
  61556. serializationObject.materials.push(subMat.id);
  61557. }
  61558. else {
  61559. serializationObject.materials.push(null);
  61560. }
  61561. }
  61562. return serializationObject;
  61563. };
  61564. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61565. var scene = this.getScene();
  61566. if (!scene) {
  61567. return;
  61568. }
  61569. var index = scene.multiMaterials.indexOf(this);
  61570. if (index >= 0) {
  61571. scene.multiMaterials.splice(index, 1);
  61572. }
  61573. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61574. };
  61575. return MultiMaterial;
  61576. }(BABYLON.Material));
  61577. BABYLON.MultiMaterial = MultiMaterial;
  61578. })(BABYLON || (BABYLON = {}));
  61579. //# sourceMappingURL=babylon.multiMaterial.js.map
  61580. var BABYLON;
  61581. (function (BABYLON) {
  61582. var FreeCameraTouchInput = /** @class */ (function () {
  61583. function FreeCameraTouchInput() {
  61584. this._offsetX = null;
  61585. this._offsetY = null;
  61586. this._pointerPressed = new Array();
  61587. this.touchAngularSensibility = 200000.0;
  61588. this.touchMoveSensibility = 250.0;
  61589. }
  61590. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61591. var _this = this;
  61592. var previousPosition = null;
  61593. if (this._pointerInput === undefined) {
  61594. this._onLostFocus = function (evt) {
  61595. _this._offsetX = null;
  61596. _this._offsetY = null;
  61597. };
  61598. this._pointerInput = function (p, s) {
  61599. var evt = p.event;
  61600. if (evt.pointerType === "mouse") {
  61601. return;
  61602. }
  61603. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61604. if (!noPreventDefault) {
  61605. evt.preventDefault();
  61606. }
  61607. _this._pointerPressed.push(evt.pointerId);
  61608. if (_this._pointerPressed.length !== 1) {
  61609. return;
  61610. }
  61611. previousPosition = {
  61612. x: evt.clientX,
  61613. y: evt.clientY
  61614. };
  61615. }
  61616. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61617. if (!noPreventDefault) {
  61618. evt.preventDefault();
  61619. }
  61620. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61621. if (index === -1) {
  61622. return;
  61623. }
  61624. _this._pointerPressed.splice(index, 1);
  61625. if (index != 0) {
  61626. return;
  61627. }
  61628. previousPosition = null;
  61629. _this._offsetX = null;
  61630. _this._offsetY = null;
  61631. }
  61632. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61633. if (!noPreventDefault) {
  61634. evt.preventDefault();
  61635. }
  61636. if (!previousPosition) {
  61637. return;
  61638. }
  61639. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61640. if (index != 0) {
  61641. return;
  61642. }
  61643. _this._offsetX = evt.clientX - previousPosition.x;
  61644. _this._offsetY = -(evt.clientY - previousPosition.y);
  61645. }
  61646. };
  61647. }
  61648. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61649. if (this._onLostFocus) {
  61650. element.addEventListener("blur", this._onLostFocus);
  61651. }
  61652. };
  61653. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61654. if (this._pointerInput && element) {
  61655. if (this._observer) {
  61656. this.camera.getScene().onPointerObservable.remove(this._observer);
  61657. this._observer = null;
  61658. }
  61659. if (this._onLostFocus) {
  61660. element.removeEventListener("blur", this._onLostFocus);
  61661. this._onLostFocus = null;
  61662. }
  61663. this._pointerPressed = [];
  61664. this._offsetX = null;
  61665. this._offsetY = null;
  61666. }
  61667. };
  61668. FreeCameraTouchInput.prototype.checkInputs = function () {
  61669. if (this._offsetX && this._offsetY) {
  61670. var camera = this.camera;
  61671. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61672. if (this._pointerPressed.length > 1) {
  61673. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61674. }
  61675. else {
  61676. var speed = camera._computeLocalCameraSpeed();
  61677. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61678. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61679. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61680. }
  61681. }
  61682. };
  61683. FreeCameraTouchInput.prototype.getClassName = function () {
  61684. return "FreeCameraTouchInput";
  61685. };
  61686. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61687. return "touch";
  61688. };
  61689. __decorate([
  61690. BABYLON.serialize()
  61691. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61692. __decorate([
  61693. BABYLON.serialize()
  61694. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61695. return FreeCameraTouchInput;
  61696. }());
  61697. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61698. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61699. })(BABYLON || (BABYLON = {}));
  61700. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61701. var BABYLON;
  61702. (function (BABYLON) {
  61703. // We're mainly based on the logic defined into the FreeCamera code
  61704. var TouchCamera = /** @class */ (function (_super) {
  61705. __extends(TouchCamera, _super);
  61706. //-- end properties for backward compatibility for inputs
  61707. function TouchCamera(name, position, scene) {
  61708. var _this = _super.call(this, name, position, scene) || this;
  61709. _this.inputs.addTouch();
  61710. _this._setupInputs();
  61711. return _this;
  61712. }
  61713. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61714. //-- Begin properties for backward compatibility for inputs
  61715. get: function () {
  61716. var touch = this.inputs.attached["touch"];
  61717. if (touch)
  61718. return touch.touchAngularSensibility;
  61719. return 0;
  61720. },
  61721. set: function (value) {
  61722. var touch = this.inputs.attached["touch"];
  61723. if (touch)
  61724. touch.touchAngularSensibility = value;
  61725. },
  61726. enumerable: true,
  61727. configurable: true
  61728. });
  61729. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61730. get: function () {
  61731. var touch = this.inputs.attached["touch"];
  61732. if (touch)
  61733. return touch.touchMoveSensibility;
  61734. return 0;
  61735. },
  61736. set: function (value) {
  61737. var touch = this.inputs.attached["touch"];
  61738. if (touch)
  61739. touch.touchMoveSensibility = value;
  61740. },
  61741. enumerable: true,
  61742. configurable: true
  61743. });
  61744. TouchCamera.prototype.getClassName = function () {
  61745. return "TouchCamera";
  61746. };
  61747. TouchCamera.prototype._setupInputs = function () {
  61748. var mouse = this.inputs.attached["mouse"];
  61749. if (mouse) {
  61750. mouse.touchEnabled = false;
  61751. }
  61752. };
  61753. return TouchCamera;
  61754. }(BABYLON.FreeCamera));
  61755. BABYLON.TouchCamera = TouchCamera;
  61756. })(BABYLON || (BABYLON = {}));
  61757. //# sourceMappingURL=babylon.touchCamera.js.map
  61758. var BABYLON;
  61759. (function (BABYLON) {
  61760. var ProceduralTexture = /** @class */ (function (_super) {
  61761. __extends(ProceduralTexture, _super);
  61762. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61763. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61764. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61765. if (isCube === void 0) { isCube = false; }
  61766. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61767. _this.isCube = isCube;
  61768. _this.isEnabled = true;
  61769. _this._currentRefreshId = -1;
  61770. _this._refreshRate = 1;
  61771. _this._vertexBuffers = {};
  61772. _this._uniforms = new Array();
  61773. _this._samplers = new Array();
  61774. _this._textures = {};
  61775. _this._floats = {};
  61776. _this._floatsArrays = {};
  61777. _this._colors3 = {};
  61778. _this._colors4 = {};
  61779. _this._vectors2 = {};
  61780. _this._vectors3 = {};
  61781. _this._matrices = {};
  61782. _this._fallbackTextureUsed = false;
  61783. scene._proceduralTextures.push(_this);
  61784. _this._engine = scene.getEngine();
  61785. _this.name = name;
  61786. _this.isRenderTarget = true;
  61787. _this._size = size;
  61788. _this._generateMipMaps = generateMipMaps;
  61789. _this.setFragment(fragment);
  61790. _this._fallbackTexture = fallbackTexture;
  61791. if (isCube) {
  61792. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61793. _this.setFloat("face", 0);
  61794. }
  61795. else {
  61796. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61797. }
  61798. // VBO
  61799. var vertices = [];
  61800. vertices.push(1, 1);
  61801. vertices.push(-1, 1);
  61802. vertices.push(-1, -1);
  61803. vertices.push(1, -1);
  61804. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61805. _this._createIndexBuffer();
  61806. return _this;
  61807. }
  61808. ProceduralTexture.prototype._createIndexBuffer = function () {
  61809. var engine = this._engine;
  61810. // Indices
  61811. var indices = [];
  61812. indices.push(0);
  61813. indices.push(1);
  61814. indices.push(2);
  61815. indices.push(0);
  61816. indices.push(2);
  61817. indices.push(3);
  61818. this._indexBuffer = engine.createIndexBuffer(indices);
  61819. };
  61820. ProceduralTexture.prototype._rebuild = function () {
  61821. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61822. if (vb) {
  61823. vb._rebuild();
  61824. }
  61825. this._createIndexBuffer();
  61826. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61827. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61828. }
  61829. };
  61830. ProceduralTexture.prototype.reset = function () {
  61831. if (this._effect === undefined) {
  61832. return;
  61833. }
  61834. var engine = this._engine;
  61835. engine._releaseEffect(this._effect);
  61836. };
  61837. ProceduralTexture.prototype.isReady = function () {
  61838. var _this = this;
  61839. var engine = this._engine;
  61840. var shaders;
  61841. if (!this._fragment) {
  61842. return false;
  61843. }
  61844. if (this._fallbackTextureUsed) {
  61845. return true;
  61846. }
  61847. if (this._fragment.fragmentElement !== undefined) {
  61848. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61849. }
  61850. else {
  61851. shaders = { vertex: "procedural", fragment: this._fragment };
  61852. }
  61853. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61854. _this.releaseInternalTexture();
  61855. if (_this._fallbackTexture) {
  61856. _this._texture = _this._fallbackTexture._texture;
  61857. if (_this._texture) {
  61858. _this._texture.incrementReferences();
  61859. }
  61860. }
  61861. _this._fallbackTextureUsed = true;
  61862. });
  61863. return this._effect.isReady();
  61864. };
  61865. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61866. this._currentRefreshId = -1;
  61867. };
  61868. ProceduralTexture.prototype.setFragment = function (fragment) {
  61869. this._fragment = fragment;
  61870. };
  61871. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61872. get: function () {
  61873. return this._refreshRate;
  61874. },
  61875. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61876. set: function (value) {
  61877. this._refreshRate = value;
  61878. this.resetRefreshCounter();
  61879. },
  61880. enumerable: true,
  61881. configurable: true
  61882. });
  61883. ProceduralTexture.prototype._shouldRender = function () {
  61884. if (!this.isEnabled || !this.isReady() || !this._texture) {
  61885. return false;
  61886. }
  61887. if (this._fallbackTextureUsed) {
  61888. return false;
  61889. }
  61890. if (this._currentRefreshId === -1) {
  61891. this._currentRefreshId = 1;
  61892. return true;
  61893. }
  61894. if (this.refreshRate === this._currentRefreshId) {
  61895. this._currentRefreshId = 1;
  61896. return true;
  61897. }
  61898. this._currentRefreshId++;
  61899. return false;
  61900. };
  61901. ProceduralTexture.prototype.getRenderSize = function () {
  61902. return this._size;
  61903. };
  61904. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  61905. if (this._fallbackTextureUsed) {
  61906. return;
  61907. }
  61908. this.releaseInternalTexture();
  61909. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  61910. };
  61911. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  61912. if (this._uniforms.indexOf(uniformName) === -1) {
  61913. this._uniforms.push(uniformName);
  61914. }
  61915. };
  61916. ProceduralTexture.prototype.setTexture = function (name, texture) {
  61917. if (this._samplers.indexOf(name) === -1) {
  61918. this._samplers.push(name);
  61919. }
  61920. this._textures[name] = texture;
  61921. return this;
  61922. };
  61923. ProceduralTexture.prototype.setFloat = function (name, value) {
  61924. this._checkUniform(name);
  61925. this._floats[name] = value;
  61926. return this;
  61927. };
  61928. ProceduralTexture.prototype.setFloats = function (name, value) {
  61929. this._checkUniform(name);
  61930. this._floatsArrays[name] = value;
  61931. return this;
  61932. };
  61933. ProceduralTexture.prototype.setColor3 = function (name, value) {
  61934. this._checkUniform(name);
  61935. this._colors3[name] = value;
  61936. return this;
  61937. };
  61938. ProceduralTexture.prototype.setColor4 = function (name, value) {
  61939. this._checkUniform(name);
  61940. this._colors4[name] = value;
  61941. return this;
  61942. };
  61943. ProceduralTexture.prototype.setVector2 = function (name, value) {
  61944. this._checkUniform(name);
  61945. this._vectors2[name] = value;
  61946. return this;
  61947. };
  61948. ProceduralTexture.prototype.setVector3 = function (name, value) {
  61949. this._checkUniform(name);
  61950. this._vectors3[name] = value;
  61951. return this;
  61952. };
  61953. ProceduralTexture.prototype.setMatrix = function (name, value) {
  61954. this._checkUniform(name);
  61955. this._matrices[name] = value;
  61956. return this;
  61957. };
  61958. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61959. var scene = this.getScene();
  61960. if (!scene) {
  61961. return;
  61962. }
  61963. var engine = this._engine;
  61964. // Render
  61965. engine.enableEffect(this._effect);
  61966. engine.setState(false);
  61967. // Texture
  61968. for (var name in this._textures) {
  61969. this._effect.setTexture(name, this._textures[name]);
  61970. }
  61971. // Float
  61972. for (name in this._floats) {
  61973. this._effect.setFloat(name, this._floats[name]);
  61974. }
  61975. // Floats
  61976. for (name in this._floatsArrays) {
  61977. this._effect.setArray(name, this._floatsArrays[name]);
  61978. }
  61979. // Color3
  61980. for (name in this._colors3) {
  61981. this._effect.setColor3(name, this._colors3[name]);
  61982. }
  61983. // Color4
  61984. for (name in this._colors4) {
  61985. var color = this._colors4[name];
  61986. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61987. }
  61988. // Vector2
  61989. for (name in this._vectors2) {
  61990. this._effect.setVector2(name, this._vectors2[name]);
  61991. }
  61992. // Vector3
  61993. for (name in this._vectors3) {
  61994. this._effect.setVector3(name, this._vectors3[name]);
  61995. }
  61996. // Matrix
  61997. for (name in this._matrices) {
  61998. this._effect.setMatrix(name, this._matrices[name]);
  61999. }
  62000. if (!this._texture) {
  62001. return;
  62002. }
  62003. if (this.isCube) {
  62004. for (var face = 0; face < 6; face++) {
  62005. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62006. // VBOs
  62007. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62008. this._effect.setFloat("face", face);
  62009. // Clear
  62010. engine.clear(scene.clearColor, true, true, true);
  62011. // Draw order
  62012. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62013. // Mipmaps
  62014. if (face === 5) {
  62015. engine.generateMipMapsForCubemap(this._texture);
  62016. }
  62017. }
  62018. }
  62019. else {
  62020. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62021. // VBOs
  62022. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62023. // Clear
  62024. engine.clear(scene.clearColor, true, true, true);
  62025. // Draw order
  62026. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62027. }
  62028. // Unbind
  62029. engine.unBindFramebuffer(this._texture, this.isCube);
  62030. if (this.onGenerated) {
  62031. this.onGenerated();
  62032. }
  62033. };
  62034. ProceduralTexture.prototype.clone = function () {
  62035. var textureSize = this.getSize();
  62036. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62037. // Base texture
  62038. newTexture.hasAlpha = this.hasAlpha;
  62039. newTexture.level = this.level;
  62040. // RenderTarget Texture
  62041. newTexture.coordinatesMode = this.coordinatesMode;
  62042. return newTexture;
  62043. };
  62044. ProceduralTexture.prototype.dispose = function () {
  62045. var scene = this.getScene();
  62046. if (!scene) {
  62047. return;
  62048. }
  62049. var index = scene._proceduralTextures.indexOf(this);
  62050. if (index >= 0) {
  62051. scene._proceduralTextures.splice(index, 1);
  62052. }
  62053. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62054. if (vertexBuffer) {
  62055. vertexBuffer.dispose();
  62056. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62057. }
  62058. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62059. this._indexBuffer = null;
  62060. }
  62061. _super.prototype.dispose.call(this);
  62062. };
  62063. return ProceduralTexture;
  62064. }(BABYLON.Texture));
  62065. BABYLON.ProceduralTexture = ProceduralTexture;
  62066. })(BABYLON || (BABYLON = {}));
  62067. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62068. var BABYLON;
  62069. (function (BABYLON) {
  62070. var CustomProceduralTexture = /** @class */ (function (_super) {
  62071. __extends(CustomProceduralTexture, _super);
  62072. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62073. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62074. _this._animate = true;
  62075. _this._time = 0;
  62076. _this._texturePath = texturePath;
  62077. //Try to load json
  62078. _this.loadJson(texturePath);
  62079. _this.refreshRate = 1;
  62080. return _this;
  62081. }
  62082. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62083. var _this = this;
  62084. var noConfigFile = function () {
  62085. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62086. try {
  62087. _this.setFragment(_this._texturePath);
  62088. }
  62089. catch (ex) {
  62090. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62091. }
  62092. };
  62093. var configFileUrl = jsonUrl + "/config.json";
  62094. var xhr = new XMLHttpRequest();
  62095. xhr.open("GET", configFileUrl, true);
  62096. xhr.addEventListener("load", function () {
  62097. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62098. try {
  62099. _this._config = JSON.parse(xhr.response);
  62100. _this.updateShaderUniforms();
  62101. _this.updateTextures();
  62102. _this.setFragment(_this._texturePath + "/custom");
  62103. _this._animate = _this._config.animate;
  62104. _this.refreshRate = _this._config.refreshrate;
  62105. }
  62106. catch (ex) {
  62107. noConfigFile();
  62108. }
  62109. }
  62110. else {
  62111. noConfigFile();
  62112. }
  62113. }, false);
  62114. xhr.addEventListener("error", function () {
  62115. noConfigFile();
  62116. }, false);
  62117. try {
  62118. xhr.send();
  62119. }
  62120. catch (ex) {
  62121. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62122. }
  62123. };
  62124. CustomProceduralTexture.prototype.isReady = function () {
  62125. if (!_super.prototype.isReady.call(this)) {
  62126. return false;
  62127. }
  62128. for (var name in this._textures) {
  62129. var texture = this._textures[name];
  62130. if (!texture.isReady()) {
  62131. return false;
  62132. }
  62133. }
  62134. return true;
  62135. };
  62136. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62137. var scene = this.getScene();
  62138. if (this._animate && scene) {
  62139. this._time += scene.getAnimationRatio() * 0.03;
  62140. this.updateShaderUniforms();
  62141. }
  62142. _super.prototype.render.call(this, useCameraPostProcess);
  62143. };
  62144. CustomProceduralTexture.prototype.updateTextures = function () {
  62145. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62146. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62147. }
  62148. };
  62149. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62150. if (this._config) {
  62151. for (var j = 0; j < this._config.uniforms.length; j++) {
  62152. var uniform = this._config.uniforms[j];
  62153. switch (uniform.type) {
  62154. case "float":
  62155. this.setFloat(uniform.name, uniform.value);
  62156. break;
  62157. case "color3":
  62158. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62159. break;
  62160. case "color4":
  62161. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62162. break;
  62163. case "vector2":
  62164. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62165. break;
  62166. case "vector3":
  62167. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62168. break;
  62169. }
  62170. }
  62171. }
  62172. this.setFloat("time", this._time);
  62173. };
  62174. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62175. get: function () {
  62176. return this._animate;
  62177. },
  62178. set: function (value) {
  62179. this._animate = value;
  62180. },
  62181. enumerable: true,
  62182. configurable: true
  62183. });
  62184. return CustomProceduralTexture;
  62185. }(BABYLON.ProceduralTexture));
  62186. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62187. })(BABYLON || (BABYLON = {}));
  62188. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62189. var BABYLON;
  62190. (function (BABYLON) {
  62191. var FreeCameraGamepadInput = /** @class */ (function () {
  62192. function FreeCameraGamepadInput() {
  62193. this.gamepadAngularSensibility = 200;
  62194. this.gamepadMoveSensibility = 40;
  62195. // private members
  62196. this._cameraTransform = BABYLON.Matrix.Identity();
  62197. this._deltaTransform = BABYLON.Vector3.Zero();
  62198. this._vector3 = BABYLON.Vector3.Zero();
  62199. this._vector2 = BABYLON.Vector2.Zero();
  62200. }
  62201. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62202. var _this = this;
  62203. var manager = this.camera.getScene().gamepadManager;
  62204. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62205. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62206. // prioritize XBOX gamepads.
  62207. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62208. _this.gamepad = gamepad;
  62209. }
  62210. }
  62211. });
  62212. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62213. if (_this.gamepad === gamepad) {
  62214. _this.gamepad = null;
  62215. }
  62216. });
  62217. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62218. };
  62219. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62220. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62221. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62222. this.gamepad = null;
  62223. };
  62224. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62225. if (this.gamepad && this.gamepad.leftStick) {
  62226. var camera = this.camera;
  62227. var LSValues = this.gamepad.leftStick;
  62228. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62229. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62230. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62231. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62232. var RSValues = this.gamepad.rightStick;
  62233. if (RSValues) {
  62234. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62235. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62236. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62237. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62238. }
  62239. else {
  62240. RSValues = { x: 0, y: 0 };
  62241. }
  62242. if (!camera.rotationQuaternion) {
  62243. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62244. }
  62245. else {
  62246. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62247. }
  62248. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62249. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62250. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62251. camera.cameraDirection.addInPlace(this._deltaTransform);
  62252. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62253. camera.cameraRotation.addInPlace(this._vector2);
  62254. }
  62255. };
  62256. FreeCameraGamepadInput.prototype.getClassName = function () {
  62257. return "FreeCameraGamepadInput";
  62258. };
  62259. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62260. return "gamepad";
  62261. };
  62262. __decorate([
  62263. BABYLON.serialize()
  62264. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62265. __decorate([
  62266. BABYLON.serialize()
  62267. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62268. return FreeCameraGamepadInput;
  62269. }());
  62270. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62271. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62272. })(BABYLON || (BABYLON = {}));
  62273. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62274. var BABYLON;
  62275. (function (BABYLON) {
  62276. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62277. function ArcRotateCameraGamepadInput() {
  62278. this.gamepadRotationSensibility = 80;
  62279. this.gamepadMoveSensibility = 40;
  62280. }
  62281. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62282. var _this = this;
  62283. var manager = this.camera.getScene().gamepadManager;
  62284. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62285. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62286. // prioritize XBOX gamepads.
  62287. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62288. _this.gamepad = gamepad;
  62289. }
  62290. }
  62291. });
  62292. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62293. if (_this.gamepad === gamepad) {
  62294. _this.gamepad = null;
  62295. }
  62296. });
  62297. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62298. };
  62299. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62300. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62301. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62302. this.gamepad = null;
  62303. };
  62304. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62305. if (this.gamepad) {
  62306. var camera = this.camera;
  62307. var RSValues = this.gamepad.rightStick;
  62308. if (RSValues) {
  62309. if (RSValues.x != 0) {
  62310. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62311. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62312. camera.inertialAlphaOffset += normalizedRX;
  62313. }
  62314. }
  62315. if (RSValues.y != 0) {
  62316. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62317. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62318. camera.inertialBetaOffset += normalizedRY;
  62319. }
  62320. }
  62321. }
  62322. var LSValues = this.gamepad.leftStick;
  62323. if (LSValues && LSValues.y != 0) {
  62324. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62325. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62326. this.camera.inertialRadiusOffset -= normalizedLY;
  62327. }
  62328. }
  62329. }
  62330. };
  62331. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62332. return "ArcRotateCameraGamepadInput";
  62333. };
  62334. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62335. return "gamepad";
  62336. };
  62337. __decorate([
  62338. BABYLON.serialize()
  62339. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62340. __decorate([
  62341. BABYLON.serialize()
  62342. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62343. return ArcRotateCameraGamepadInput;
  62344. }());
  62345. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62346. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62347. })(BABYLON || (BABYLON = {}));
  62348. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62349. var BABYLON;
  62350. (function (BABYLON) {
  62351. var GamepadManager = /** @class */ (function () {
  62352. function GamepadManager(_scene) {
  62353. var _this = this;
  62354. this._scene = _scene;
  62355. this._babylonGamepads = [];
  62356. this._oneGamepadConnected = false;
  62357. this._isMonitoring = false;
  62358. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62359. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62360. this._gamepadEventSupported = false;
  62361. }
  62362. else {
  62363. this._gamepadEventSupported = 'GamepadEvent' in window;
  62364. this._gamepadSupport = (navigator.getGamepads ||
  62365. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62366. }
  62367. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62368. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62369. for (var i in _this._babylonGamepads) {
  62370. var gamepad = _this._babylonGamepads[i];
  62371. if (gamepad && gamepad._isConnected) {
  62372. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62373. }
  62374. }
  62375. });
  62376. this._onGamepadConnectedEvent = function (evt) {
  62377. var gamepad = evt.gamepad;
  62378. if (gamepad.index in _this._babylonGamepads) {
  62379. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62380. return;
  62381. }
  62382. }
  62383. var newGamepad;
  62384. if (_this._babylonGamepads[gamepad.index]) {
  62385. newGamepad = _this._babylonGamepads[gamepad.index];
  62386. newGamepad.browserGamepad = gamepad;
  62387. newGamepad._isConnected = true;
  62388. }
  62389. else {
  62390. newGamepad = _this._addNewGamepad(gamepad);
  62391. }
  62392. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62393. _this._startMonitoringGamepads();
  62394. };
  62395. this._onGamepadDisconnectedEvent = function (evt) {
  62396. var gamepad = evt.gamepad;
  62397. // Remove the gamepad from the list of gamepads to monitor.
  62398. for (var i in _this._babylonGamepads) {
  62399. if (_this._babylonGamepads[i].index === gamepad.index) {
  62400. var disconnectedGamepad = _this._babylonGamepads[i];
  62401. disconnectedGamepad._isConnected = false;
  62402. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62403. break;
  62404. }
  62405. }
  62406. };
  62407. if (this._gamepadSupport) {
  62408. //first add already-connected gamepads
  62409. this._updateGamepadObjects();
  62410. if (this._babylonGamepads.length) {
  62411. this._startMonitoringGamepads();
  62412. }
  62413. // Checking if the gamepad connected event is supported (like in Firefox)
  62414. if (this._gamepadEventSupported) {
  62415. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62416. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62417. }
  62418. else {
  62419. this._startMonitoringGamepads();
  62420. }
  62421. }
  62422. }
  62423. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62424. get: function () {
  62425. return this._babylonGamepads;
  62426. },
  62427. enumerable: true,
  62428. configurable: true
  62429. });
  62430. GamepadManager.prototype.getGamepadByType = function (type) {
  62431. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62432. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62433. var gamepad = _a[_i];
  62434. if (gamepad && gamepad.type === type) {
  62435. return gamepad;
  62436. }
  62437. }
  62438. return null;
  62439. };
  62440. GamepadManager.prototype.dispose = function () {
  62441. if (this._gamepadEventSupported) {
  62442. if (this._onGamepadConnectedEvent) {
  62443. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62444. }
  62445. if (this._onGamepadDisconnectedEvent) {
  62446. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62447. }
  62448. this._onGamepadConnectedEvent = null;
  62449. this._onGamepadDisconnectedEvent = null;
  62450. }
  62451. this._babylonGamepads.forEach(function (gamepad) {
  62452. gamepad.dispose();
  62453. });
  62454. this.onGamepadConnectedObservable.clear();
  62455. this.onGamepadDisconnectedObservable.clear();
  62456. this._oneGamepadConnected = false;
  62457. this._stopMonitoringGamepads();
  62458. this._babylonGamepads = [];
  62459. };
  62460. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62461. if (!this._oneGamepadConnected) {
  62462. this._oneGamepadConnected = true;
  62463. }
  62464. var newGamepad;
  62465. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62466. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62467. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62468. }
  62469. else if (gamepad.pose) {
  62470. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62471. }
  62472. else {
  62473. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62474. }
  62475. this._babylonGamepads[newGamepad.index] = newGamepad;
  62476. return newGamepad;
  62477. };
  62478. GamepadManager.prototype._startMonitoringGamepads = function () {
  62479. if (!this._isMonitoring) {
  62480. this._isMonitoring = true;
  62481. //back-comp
  62482. if (!this._scene) {
  62483. this._checkGamepadsStatus();
  62484. }
  62485. }
  62486. };
  62487. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62488. this._isMonitoring = false;
  62489. };
  62490. GamepadManager.prototype._checkGamepadsStatus = function () {
  62491. var _this = this;
  62492. // Hack to be compatible Chrome
  62493. this._updateGamepadObjects();
  62494. for (var i in this._babylonGamepads) {
  62495. var gamepad = this._babylonGamepads[i];
  62496. if (!gamepad || !gamepad.isConnected) {
  62497. continue;
  62498. }
  62499. gamepad.update();
  62500. }
  62501. if (this._isMonitoring && !this._scene) {
  62502. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62503. }
  62504. };
  62505. // This function is called only on Chrome, which does not properly support
  62506. // connection/disconnection events and forces you to recopy again the gamepad object
  62507. GamepadManager.prototype._updateGamepadObjects = function () {
  62508. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62509. for (var i = 0; i < gamepads.length; i++) {
  62510. if (gamepads[i]) {
  62511. if (!this._babylonGamepads[gamepads[i].index]) {
  62512. var newGamepad = this._addNewGamepad(gamepads[i]);
  62513. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62514. }
  62515. else {
  62516. // Forced to copy again this object for Chrome for unknown reason
  62517. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62518. if (!this._babylonGamepads[i].isConnected) {
  62519. this._babylonGamepads[i]._isConnected = true;
  62520. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62521. }
  62522. }
  62523. }
  62524. }
  62525. };
  62526. return GamepadManager;
  62527. }());
  62528. BABYLON.GamepadManager = GamepadManager;
  62529. })(BABYLON || (BABYLON = {}));
  62530. //# sourceMappingURL=babylon.gamepadManager.js.map
  62531. var BABYLON;
  62532. (function (BABYLON) {
  62533. var StickValues = /** @class */ (function () {
  62534. function StickValues(x, y) {
  62535. this.x = x;
  62536. this.y = y;
  62537. }
  62538. return StickValues;
  62539. }());
  62540. BABYLON.StickValues = StickValues;
  62541. var Gamepad = /** @class */ (function () {
  62542. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62543. if (leftStickX === void 0) { leftStickX = 0; }
  62544. if (leftStickY === void 0) { leftStickY = 1; }
  62545. if (rightStickX === void 0) { rightStickX = 2; }
  62546. if (rightStickY === void 0) { rightStickY = 3; }
  62547. this.id = id;
  62548. this.index = index;
  62549. this.browserGamepad = browserGamepad;
  62550. this._isConnected = true;
  62551. this._invertLeftStickY = false;
  62552. this.type = Gamepad.GAMEPAD;
  62553. this._leftStickAxisX = leftStickX;
  62554. this._leftStickAxisY = leftStickY;
  62555. this._rightStickAxisX = rightStickX;
  62556. this._rightStickAxisY = rightStickY;
  62557. if (this.browserGamepad.axes.length >= 2) {
  62558. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62559. }
  62560. if (this.browserGamepad.axes.length >= 4) {
  62561. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62562. }
  62563. }
  62564. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62565. get: function () {
  62566. return this._isConnected;
  62567. },
  62568. enumerable: true,
  62569. configurable: true
  62570. });
  62571. Gamepad.prototype.onleftstickchanged = function (callback) {
  62572. this._onleftstickchanged = callback;
  62573. };
  62574. Gamepad.prototype.onrightstickchanged = function (callback) {
  62575. this._onrightstickchanged = callback;
  62576. };
  62577. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62578. get: function () {
  62579. return this._leftStick;
  62580. },
  62581. set: function (newValues) {
  62582. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62583. this._onleftstickchanged(newValues);
  62584. }
  62585. this._leftStick = newValues;
  62586. },
  62587. enumerable: true,
  62588. configurable: true
  62589. });
  62590. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62591. get: function () {
  62592. return this._rightStick;
  62593. },
  62594. set: function (newValues) {
  62595. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62596. this._onrightstickchanged(newValues);
  62597. }
  62598. this._rightStick = newValues;
  62599. },
  62600. enumerable: true,
  62601. configurable: true
  62602. });
  62603. Gamepad.prototype.update = function () {
  62604. if (this._leftStick) {
  62605. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62606. if (this._invertLeftStickY) {
  62607. this.leftStick.y *= -1;
  62608. }
  62609. }
  62610. if (this._rightStick) {
  62611. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62612. }
  62613. };
  62614. Gamepad.prototype.dispose = function () {
  62615. };
  62616. Gamepad.GAMEPAD = 0;
  62617. Gamepad.GENERIC = 1;
  62618. Gamepad.XBOX = 2;
  62619. Gamepad.POSE_ENABLED = 3;
  62620. return Gamepad;
  62621. }());
  62622. BABYLON.Gamepad = Gamepad;
  62623. var GenericPad = /** @class */ (function (_super) {
  62624. __extends(GenericPad, _super);
  62625. function GenericPad(id, index, browserGamepad) {
  62626. var _this = _super.call(this, id, index, browserGamepad) || this;
  62627. _this.onButtonDownObservable = new BABYLON.Observable();
  62628. _this.onButtonUpObservable = new BABYLON.Observable();
  62629. _this.type = Gamepad.GENERIC;
  62630. _this._buttons = new Array(browserGamepad.buttons.length);
  62631. return _this;
  62632. }
  62633. GenericPad.prototype.onbuttondown = function (callback) {
  62634. this._onbuttondown = callback;
  62635. };
  62636. GenericPad.prototype.onbuttonup = function (callback) {
  62637. this._onbuttonup = callback;
  62638. };
  62639. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62640. if (newValue !== currentValue) {
  62641. if (newValue === 1) {
  62642. if (this._onbuttondown) {
  62643. this._onbuttondown(buttonIndex);
  62644. }
  62645. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62646. }
  62647. if (newValue === 0) {
  62648. if (this._onbuttonup) {
  62649. this._onbuttonup(buttonIndex);
  62650. }
  62651. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62652. }
  62653. }
  62654. return newValue;
  62655. };
  62656. GenericPad.prototype.update = function () {
  62657. _super.prototype.update.call(this);
  62658. for (var index = 0; index < this._buttons.length; index++) {
  62659. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62660. }
  62661. };
  62662. GenericPad.prototype.dispose = function () {
  62663. _super.prototype.dispose.call(this);
  62664. this.onButtonDownObservable.clear();
  62665. this.onButtonUpObservable.clear();
  62666. };
  62667. return GenericPad;
  62668. }(Gamepad));
  62669. BABYLON.GenericPad = GenericPad;
  62670. })(BABYLON || (BABYLON = {}));
  62671. //# sourceMappingURL=babylon.gamepad.js.map
  62672. var BABYLON;
  62673. (function (BABYLON) {
  62674. var Xbox360Button;
  62675. (function (Xbox360Button) {
  62676. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62677. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62678. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62679. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62680. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62681. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62682. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62683. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62684. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62685. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62686. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62687. var Xbox360Dpad;
  62688. (function (Xbox360Dpad) {
  62689. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62690. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62691. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62692. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62693. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62694. var Xbox360Pad = /** @class */ (function (_super) {
  62695. __extends(Xbox360Pad, _super);
  62696. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62697. if (xboxOne === void 0) { xboxOne = false; }
  62698. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62699. _this._leftTrigger = 0;
  62700. _this._rightTrigger = 0;
  62701. _this.onButtonDownObservable = new BABYLON.Observable();
  62702. _this.onButtonUpObservable = new BABYLON.Observable();
  62703. _this.onPadDownObservable = new BABYLON.Observable();
  62704. _this.onPadUpObservable = new BABYLON.Observable();
  62705. _this._buttonA = 0;
  62706. _this._buttonB = 0;
  62707. _this._buttonX = 0;
  62708. _this._buttonY = 0;
  62709. _this._buttonBack = 0;
  62710. _this._buttonStart = 0;
  62711. _this._buttonLB = 0;
  62712. _this._buttonRB = 0;
  62713. _this._buttonLeftStick = 0;
  62714. _this._buttonRightStick = 0;
  62715. _this._dPadUp = 0;
  62716. _this._dPadDown = 0;
  62717. _this._dPadLeft = 0;
  62718. _this._dPadRight = 0;
  62719. _this._isXboxOnePad = false;
  62720. _this.type = BABYLON.Gamepad.XBOX;
  62721. _this._isXboxOnePad = xboxOne;
  62722. return _this;
  62723. }
  62724. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62725. this._onlefttriggerchanged = callback;
  62726. };
  62727. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62728. this._onrighttriggerchanged = callback;
  62729. };
  62730. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62731. get: function () {
  62732. return this._leftTrigger;
  62733. },
  62734. set: function (newValue) {
  62735. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62736. this._onlefttriggerchanged(newValue);
  62737. }
  62738. this._leftTrigger = newValue;
  62739. },
  62740. enumerable: true,
  62741. configurable: true
  62742. });
  62743. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62744. get: function () {
  62745. return this._rightTrigger;
  62746. },
  62747. set: function (newValue) {
  62748. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62749. this._onrighttriggerchanged(newValue);
  62750. }
  62751. this._rightTrigger = newValue;
  62752. },
  62753. enumerable: true,
  62754. configurable: true
  62755. });
  62756. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62757. this._onbuttondown = callback;
  62758. };
  62759. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62760. this._onbuttonup = callback;
  62761. };
  62762. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62763. this._ondpaddown = callback;
  62764. };
  62765. Xbox360Pad.prototype.ondpadup = function (callback) {
  62766. this._ondpadup = callback;
  62767. };
  62768. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62769. if (newValue !== currentValue) {
  62770. if (newValue === 1) {
  62771. if (this._onbuttondown) {
  62772. this._onbuttondown(buttonType);
  62773. }
  62774. this.onButtonDownObservable.notifyObservers(buttonType);
  62775. }
  62776. if (newValue === 0) {
  62777. if (this._onbuttonup) {
  62778. this._onbuttonup(buttonType);
  62779. }
  62780. this.onButtonUpObservable.notifyObservers(buttonType);
  62781. }
  62782. }
  62783. return newValue;
  62784. };
  62785. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62786. if (newValue !== currentValue) {
  62787. if (newValue === 1) {
  62788. if (this._ondpaddown) {
  62789. this._ondpaddown(buttonType);
  62790. }
  62791. this.onPadDownObservable.notifyObservers(buttonType);
  62792. }
  62793. if (newValue === 0) {
  62794. if (this._ondpadup) {
  62795. this._ondpadup(buttonType);
  62796. }
  62797. this.onPadUpObservable.notifyObservers(buttonType);
  62798. }
  62799. }
  62800. return newValue;
  62801. };
  62802. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62803. get: function () {
  62804. return this._buttonA;
  62805. },
  62806. set: function (value) {
  62807. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62808. },
  62809. enumerable: true,
  62810. configurable: true
  62811. });
  62812. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62813. get: function () {
  62814. return this._buttonB;
  62815. },
  62816. set: function (value) {
  62817. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62818. },
  62819. enumerable: true,
  62820. configurable: true
  62821. });
  62822. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62823. get: function () {
  62824. return this._buttonX;
  62825. },
  62826. set: function (value) {
  62827. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62828. },
  62829. enumerable: true,
  62830. configurable: true
  62831. });
  62832. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62833. get: function () {
  62834. return this._buttonY;
  62835. },
  62836. set: function (value) {
  62837. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62838. },
  62839. enumerable: true,
  62840. configurable: true
  62841. });
  62842. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62843. get: function () {
  62844. return this._buttonStart;
  62845. },
  62846. set: function (value) {
  62847. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62848. },
  62849. enumerable: true,
  62850. configurable: true
  62851. });
  62852. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62853. get: function () {
  62854. return this._buttonBack;
  62855. },
  62856. set: function (value) {
  62857. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62858. },
  62859. enumerable: true,
  62860. configurable: true
  62861. });
  62862. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62863. get: function () {
  62864. return this._buttonLB;
  62865. },
  62866. set: function (value) {
  62867. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62868. },
  62869. enumerable: true,
  62870. configurable: true
  62871. });
  62872. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62873. get: function () {
  62874. return this._buttonRB;
  62875. },
  62876. set: function (value) {
  62877. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  62878. },
  62879. enumerable: true,
  62880. configurable: true
  62881. });
  62882. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  62883. get: function () {
  62884. return this._buttonLeftStick;
  62885. },
  62886. set: function (value) {
  62887. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  62888. },
  62889. enumerable: true,
  62890. configurable: true
  62891. });
  62892. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  62893. get: function () {
  62894. return this._buttonRightStick;
  62895. },
  62896. set: function (value) {
  62897. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  62898. },
  62899. enumerable: true,
  62900. configurable: true
  62901. });
  62902. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  62903. get: function () {
  62904. return this._dPadUp;
  62905. },
  62906. set: function (value) {
  62907. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  62908. },
  62909. enumerable: true,
  62910. configurable: true
  62911. });
  62912. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  62913. get: function () {
  62914. return this._dPadDown;
  62915. },
  62916. set: function (value) {
  62917. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  62918. },
  62919. enumerable: true,
  62920. configurable: true
  62921. });
  62922. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  62923. get: function () {
  62924. return this._dPadLeft;
  62925. },
  62926. set: function (value) {
  62927. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  62928. },
  62929. enumerable: true,
  62930. configurable: true
  62931. });
  62932. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  62933. get: function () {
  62934. return this._dPadRight;
  62935. },
  62936. set: function (value) {
  62937. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  62938. },
  62939. enumerable: true,
  62940. configurable: true
  62941. });
  62942. Xbox360Pad.prototype.update = function () {
  62943. _super.prototype.update.call(this);
  62944. if (this._isXboxOnePad) {
  62945. this.buttonA = this.browserGamepad.buttons[0].value;
  62946. this.buttonB = this.browserGamepad.buttons[1].value;
  62947. this.buttonX = this.browserGamepad.buttons[2].value;
  62948. this.buttonY = this.browserGamepad.buttons[3].value;
  62949. this.buttonLB = this.browserGamepad.buttons[4].value;
  62950. this.buttonRB = this.browserGamepad.buttons[5].value;
  62951. this.leftTrigger = this.browserGamepad.axes[2];
  62952. this.rightTrigger = this.browserGamepad.axes[5];
  62953. this.buttonBack = this.browserGamepad.buttons[9].value;
  62954. this.buttonStart = this.browserGamepad.buttons[8].value;
  62955. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  62956. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  62957. this.dPadUp = this.browserGamepad.buttons[11].value;
  62958. this.dPadDown = this.browserGamepad.buttons[12].value;
  62959. this.dPadLeft = this.browserGamepad.buttons[13].value;
  62960. this.dPadRight = this.browserGamepad.buttons[14].value;
  62961. }
  62962. else {
  62963. this.buttonA = this.browserGamepad.buttons[0].value;
  62964. this.buttonB = this.browserGamepad.buttons[1].value;
  62965. this.buttonX = this.browserGamepad.buttons[2].value;
  62966. this.buttonY = this.browserGamepad.buttons[3].value;
  62967. this.buttonLB = this.browserGamepad.buttons[4].value;
  62968. this.buttonRB = this.browserGamepad.buttons[5].value;
  62969. this.leftTrigger = this.browserGamepad.buttons[6].value;
  62970. this.rightTrigger = this.browserGamepad.buttons[7].value;
  62971. this.buttonBack = this.browserGamepad.buttons[8].value;
  62972. this.buttonStart = this.browserGamepad.buttons[9].value;
  62973. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  62974. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  62975. this.dPadUp = this.browserGamepad.buttons[12].value;
  62976. this.dPadDown = this.browserGamepad.buttons[13].value;
  62977. this.dPadLeft = this.browserGamepad.buttons[14].value;
  62978. this.dPadRight = this.browserGamepad.buttons[15].value;
  62979. }
  62980. };
  62981. Xbox360Pad.prototype.dispose = function () {
  62982. _super.prototype.dispose.call(this);
  62983. this.onButtonDownObservable.clear();
  62984. this.onButtonUpObservable.clear();
  62985. this.onPadDownObservable.clear();
  62986. this.onPadUpObservable.clear();
  62987. };
  62988. return Xbox360Pad;
  62989. }(BABYLON.Gamepad));
  62990. BABYLON.Xbox360Pad = Xbox360Pad;
  62991. })(BABYLON || (BABYLON = {}));
  62992. //# sourceMappingURL=babylon.xboxGamepad.js.map
  62993. var BABYLON;
  62994. (function (BABYLON) {
  62995. var PoseEnabledControllerType;
  62996. (function (PoseEnabledControllerType) {
  62997. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  62998. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  62999. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63000. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63001. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63002. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63003. var PoseEnabledControllerHelper = /** @class */ (function () {
  63004. function PoseEnabledControllerHelper() {
  63005. }
  63006. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63007. // Oculus Touch
  63008. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63009. return new BABYLON.OculusTouchController(vrGamepad);
  63010. }
  63011. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63012. return new BABYLON.WindowsMotionController(vrGamepad);
  63013. }
  63014. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63015. return new BABYLON.ViveController(vrGamepad);
  63016. }
  63017. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63018. return new BABYLON.GearVRController(vrGamepad);
  63019. }
  63020. else {
  63021. return new BABYLON.GenericController(vrGamepad);
  63022. }
  63023. };
  63024. return PoseEnabledControllerHelper;
  63025. }());
  63026. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63027. var PoseEnabledController = /** @class */ (function (_super) {
  63028. __extends(PoseEnabledController, _super);
  63029. function PoseEnabledController(browserGamepad) {
  63030. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63031. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63032. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63033. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63034. // Represents device position and rotation in babylon space
  63035. _this.devicePosition = BABYLON.Vector3.Zero();
  63036. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63037. _this.deviceScaleFactor = 1;
  63038. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63039. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63040. _this._workingMatrix = BABYLON.Matrix.Identity();
  63041. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63042. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63043. _this.position = BABYLON.Vector3.Zero();
  63044. _this.rotationQuaternion = new BABYLON.Quaternion();
  63045. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63046. _this._calculatedRotation = new BABYLON.Quaternion();
  63047. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63048. return _this;
  63049. }
  63050. PoseEnabledController.prototype.update = function () {
  63051. _super.prototype.update.call(this);
  63052. var pose = this.browserGamepad.pose;
  63053. this.updateFromDevice(pose);
  63054. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63055. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63056. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63057. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63058. if (this._mesh) {
  63059. this._mesh.position.copyFrom(this.devicePosition);
  63060. if (this._mesh.rotationQuaternion) {
  63061. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63062. }
  63063. }
  63064. };
  63065. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63066. if (poseData) {
  63067. this.rawPose = poseData;
  63068. if (poseData.position) {
  63069. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63070. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63071. this._deviceRoomPosition.z *= -1;
  63072. }
  63073. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63074. this._calculatedPosition.addInPlace(this.position);
  63075. }
  63076. var pose = this.rawPose;
  63077. if (poseData.orientation && pose.orientation) {
  63078. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63079. if (this._mesh) {
  63080. if (this._mesh.getScene().useRightHandedSystem) {
  63081. this._deviceRoomRotationQuaternion.z *= -1;
  63082. this._deviceRoomRotationQuaternion.w *= -1;
  63083. }
  63084. else {
  63085. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63086. }
  63087. }
  63088. // if the camera is set, rotate to the camera's rotation
  63089. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63090. }
  63091. }
  63092. };
  63093. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63094. if (this._mesh) {
  63095. this._mesh.parent = null;
  63096. }
  63097. this._mesh = mesh;
  63098. if (this._poseControlledCamera) {
  63099. this._mesh.parent = this._poseControlledCamera;
  63100. }
  63101. if (!this._mesh.rotationQuaternion) {
  63102. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63103. }
  63104. };
  63105. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63106. this._poseControlledCamera = camera;
  63107. if (this._mesh) {
  63108. this._mesh.parent = this._poseControlledCamera;
  63109. }
  63110. };
  63111. PoseEnabledController.prototype.dispose = function () {
  63112. if (this._mesh) {
  63113. this._mesh.dispose();
  63114. }
  63115. this._mesh = null;
  63116. _super.prototype.dispose.call(this);
  63117. };
  63118. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63119. get: function () {
  63120. return this._mesh;
  63121. },
  63122. enumerable: true,
  63123. configurable: true
  63124. });
  63125. PoseEnabledController.prototype.getForwardRay = function (length) {
  63126. if (length === void 0) { length = 100; }
  63127. if (!this.mesh) {
  63128. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63129. }
  63130. var m = this.mesh.getWorldMatrix();
  63131. var origin = m.getTranslation();
  63132. var forward = new BABYLON.Vector3(0, 0, -1);
  63133. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63134. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63135. return new BABYLON.Ray(origin, direction, length);
  63136. };
  63137. return PoseEnabledController;
  63138. }(BABYLON.Gamepad));
  63139. BABYLON.PoseEnabledController = PoseEnabledController;
  63140. })(BABYLON || (BABYLON = {}));
  63141. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63142. var BABYLON;
  63143. (function (BABYLON) {
  63144. var WebVRController = /** @class */ (function (_super) {
  63145. __extends(WebVRController, _super);
  63146. function WebVRController(vrGamepad) {
  63147. var _this = _super.call(this, vrGamepad) || this;
  63148. // Observables
  63149. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63150. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63151. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63152. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63153. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63154. _this.pad = { x: 0, y: 0 };
  63155. // avoid GC, store state in a tmp object
  63156. _this._changes = {
  63157. pressChanged: false,
  63158. touchChanged: false,
  63159. valueChanged: false,
  63160. changed: false
  63161. };
  63162. _this._buttons = new Array(vrGamepad.buttons.length);
  63163. _this.hand = vrGamepad.hand;
  63164. return _this;
  63165. }
  63166. WebVRController.prototype.onButtonStateChange = function (callback) {
  63167. this._onButtonStateChange = callback;
  63168. };
  63169. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63170. get: function () {
  63171. return this._defaultModel;
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. WebVRController.prototype.update = function () {
  63177. _super.prototype.update.call(this);
  63178. for (var index = 0; index < this._buttons.length; index++) {
  63179. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63180. }
  63181. ;
  63182. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63183. this.pad.x = this.leftStick.x;
  63184. this.pad.y = this.leftStick.y;
  63185. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63186. }
  63187. };
  63188. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63189. if (!newState) {
  63190. newState = {
  63191. pressed: false,
  63192. touched: false,
  63193. value: 0
  63194. };
  63195. }
  63196. if (!currentState) {
  63197. this._buttons[buttonIndex] = {
  63198. pressed: newState.pressed,
  63199. touched: newState.touched,
  63200. value: newState.value
  63201. };
  63202. return;
  63203. }
  63204. this._checkChanges(newState, currentState);
  63205. if (this._changes.changed) {
  63206. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63207. this.handleButtonChange(buttonIndex, newState, this._changes);
  63208. }
  63209. this._buttons[buttonIndex].pressed = newState.pressed;
  63210. this._buttons[buttonIndex].touched = newState.touched;
  63211. // oculus triggers are never 0, thou not touched.
  63212. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63213. };
  63214. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63215. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63216. this._changes.touchChanged = newState.touched !== currentState.touched;
  63217. this._changes.valueChanged = newState.value !== currentState.value;
  63218. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63219. return this._changes;
  63220. };
  63221. WebVRController.prototype.dispose = function () {
  63222. _super.prototype.dispose.call(this);
  63223. this.onTriggerStateChangedObservable.clear();
  63224. this.onMainButtonStateChangedObservable.clear();
  63225. this.onSecondaryButtonStateChangedObservable.clear();
  63226. this.onPadStateChangedObservable.clear();
  63227. this.onPadValuesChangedObservable.clear();
  63228. };
  63229. return WebVRController;
  63230. }(BABYLON.PoseEnabledController));
  63231. BABYLON.WebVRController = WebVRController;
  63232. })(BABYLON || (BABYLON = {}));
  63233. //# sourceMappingURL=babylon.webVRController.js.map
  63234. var BABYLON;
  63235. (function (BABYLON) {
  63236. var OculusTouchController = /** @class */ (function (_super) {
  63237. __extends(OculusTouchController, _super);
  63238. function OculusTouchController(vrGamepad) {
  63239. var _this = _super.call(this, vrGamepad) || this;
  63240. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63241. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63242. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63243. return _this;
  63244. }
  63245. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63246. var _this = this;
  63247. var meshName;
  63248. // Hand
  63249. if (this.hand === 'left') {
  63250. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63251. }
  63252. else {
  63253. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63254. }
  63255. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63256. /*
  63257. Parent Mesh name: oculus_touch_left
  63258. - body
  63259. - trigger
  63260. - thumbstick
  63261. - grip
  63262. - button_y
  63263. - button_x
  63264. - button_enter
  63265. */
  63266. _this._defaultModel = newMeshes[1];
  63267. _this.attachToMesh(_this._defaultModel);
  63268. if (meshLoaded) {
  63269. meshLoaded(_this._defaultModel);
  63270. }
  63271. });
  63272. };
  63273. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63274. // helper getters for left and right hand.
  63275. get: function () {
  63276. if (this.hand === 'right') {
  63277. return this.onMainButtonStateChangedObservable;
  63278. }
  63279. else {
  63280. throw new Error('No A button on left hand');
  63281. }
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63287. get: function () {
  63288. if (this.hand === 'right') {
  63289. return this.onSecondaryButtonStateChangedObservable;
  63290. }
  63291. else {
  63292. throw new Error('No B button on left hand');
  63293. }
  63294. },
  63295. enumerable: true,
  63296. configurable: true
  63297. });
  63298. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63299. get: function () {
  63300. if (this.hand === 'left') {
  63301. return this.onMainButtonStateChangedObservable;
  63302. }
  63303. else {
  63304. throw new Error('No X button on right hand');
  63305. }
  63306. },
  63307. enumerable: true,
  63308. configurable: true
  63309. });
  63310. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63311. get: function () {
  63312. if (this.hand === 'left') {
  63313. return this.onSecondaryButtonStateChangedObservable;
  63314. }
  63315. else {
  63316. throw new Error('No Y button on right hand');
  63317. }
  63318. },
  63319. enumerable: true,
  63320. configurable: true
  63321. });
  63322. /*
  63323. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63324. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63325. 2) secondary trigger (same)
  63326. 3) A (right) X (left), touch, pressed = value
  63327. 4) B / Y
  63328. 5) thumb rest
  63329. */
  63330. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63331. var notifyObject = state; //{ state: state, changes: changes };
  63332. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63333. switch (buttonIdx) {
  63334. case 0:
  63335. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63336. return;
  63337. case 1:// index trigger
  63338. if (this._defaultModel) {
  63339. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63340. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63341. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63342. }
  63343. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63344. return;
  63345. case 2:// secondary trigger
  63346. if (this._defaultModel) {
  63347. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63348. }
  63349. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63350. return;
  63351. case 3:
  63352. if (this._defaultModel) {
  63353. if (notifyObject.pressed) {
  63354. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63355. }
  63356. else {
  63357. (this._defaultModel.getChildren()[1]).position.y = 0;
  63358. }
  63359. }
  63360. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63361. return;
  63362. case 4:
  63363. if (this._defaultModel) {
  63364. if (notifyObject.pressed) {
  63365. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63366. }
  63367. else {
  63368. (this._defaultModel.getChildren()[2]).position.y = 0;
  63369. }
  63370. }
  63371. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63372. return;
  63373. case 5:
  63374. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63375. return;
  63376. }
  63377. };
  63378. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63379. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63380. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63381. return OculusTouchController;
  63382. }(BABYLON.WebVRController));
  63383. BABYLON.OculusTouchController = OculusTouchController;
  63384. })(BABYLON || (BABYLON = {}));
  63385. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63386. var BABYLON;
  63387. (function (BABYLON) {
  63388. var ViveController = /** @class */ (function (_super) {
  63389. __extends(ViveController, _super);
  63390. function ViveController(vrGamepad) {
  63391. var _this = _super.call(this, vrGamepad) || this;
  63392. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63393. _this._invertLeftStickY = true;
  63394. return _this;
  63395. }
  63396. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63397. var _this = this;
  63398. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63399. /*
  63400. Parent Mesh name: ViveWand
  63401. - body
  63402. - r_gripper
  63403. - l_gripper
  63404. - menu_button
  63405. - system_button
  63406. - trackpad
  63407. - trigger
  63408. - LED
  63409. */
  63410. _this._defaultModel = newMeshes[1];
  63411. _this.attachToMesh(_this._defaultModel);
  63412. if (meshLoaded) {
  63413. meshLoaded(_this._defaultModel);
  63414. }
  63415. });
  63416. };
  63417. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63418. get: function () {
  63419. return this.onMainButtonStateChangedObservable;
  63420. },
  63421. enumerable: true,
  63422. configurable: true
  63423. });
  63424. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63425. get: function () {
  63426. return this.onMainButtonStateChangedObservable;
  63427. },
  63428. enumerable: true,
  63429. configurable: true
  63430. });
  63431. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63432. get: function () {
  63433. return this.onSecondaryButtonStateChangedObservable;
  63434. },
  63435. enumerable: true,
  63436. configurable: true
  63437. });
  63438. /**
  63439. * Vive mapping:
  63440. * 0: touchpad
  63441. * 1: trigger
  63442. * 2: left AND right buttons
  63443. * 3: menu button
  63444. */
  63445. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63446. var notifyObject = state; //{ state: state, changes: changes };
  63447. switch (buttonIdx) {
  63448. case 0:
  63449. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63450. return;
  63451. case 1:// index trigger
  63452. if (this._defaultModel) {
  63453. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63454. }
  63455. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63456. return;
  63457. case 2:// left AND right button
  63458. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63459. return;
  63460. case 3:
  63461. if (this._defaultModel) {
  63462. if (notifyObject.pressed) {
  63463. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63464. }
  63465. else {
  63466. (this._defaultModel.getChildren()[2]).position.y = 0;
  63467. }
  63468. }
  63469. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63470. return;
  63471. }
  63472. };
  63473. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63474. ViveController.MODEL_FILENAME = 'wand.babylon';
  63475. return ViveController;
  63476. }(BABYLON.WebVRController));
  63477. BABYLON.ViveController = ViveController;
  63478. })(BABYLON || (BABYLON = {}));
  63479. //# sourceMappingURL=babylon.viveController.js.map
  63480. var BABYLON;
  63481. (function (BABYLON) {
  63482. var GenericController = /** @class */ (function (_super) {
  63483. __extends(GenericController, _super);
  63484. function GenericController(vrGamepad) {
  63485. return _super.call(this, vrGamepad) || this;
  63486. }
  63487. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63488. var _this = this;
  63489. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63490. _this._defaultModel = newMeshes[1];
  63491. _this.attachToMesh(_this._defaultModel);
  63492. if (meshLoaded) {
  63493. meshLoaded(_this._defaultModel);
  63494. }
  63495. });
  63496. };
  63497. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63498. console.log("Button id: " + buttonIdx + "state: ");
  63499. console.dir(state);
  63500. };
  63501. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63502. GenericController.MODEL_FILENAME = 'generic.babylon';
  63503. return GenericController;
  63504. }(BABYLON.WebVRController));
  63505. BABYLON.GenericController = GenericController;
  63506. })(BABYLON || (BABYLON = {}));
  63507. //# sourceMappingURL=babylon.genericController.js.map
  63508. var BABYLON;
  63509. (function (BABYLON) {
  63510. var LoadedMeshInfo = /** @class */ (function () {
  63511. function LoadedMeshInfo() {
  63512. this.buttonMeshes = {};
  63513. this.axisMeshes = {};
  63514. }
  63515. return LoadedMeshInfo;
  63516. }());
  63517. var WindowsMotionController = /** @class */ (function (_super) {
  63518. __extends(WindowsMotionController, _super);
  63519. function WindowsMotionController(vrGamepad) {
  63520. var _this = _super.call(this, vrGamepad) || this;
  63521. _this._mapping = {
  63522. // Semantic button names
  63523. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63524. // A mapping of the button name to glTF model node name
  63525. // that should be transformed by button value.
  63526. buttonMeshNames: {
  63527. 'trigger': 'SELECT',
  63528. 'menu': 'MENU',
  63529. 'grip': 'GRASP',
  63530. 'thumbstick': 'THUMBSTICK_PRESS',
  63531. 'trackpad': 'TOUCHPAD_PRESS'
  63532. },
  63533. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63534. buttonObservableNames: {
  63535. 'trigger': 'onTriggerStateChangedObservable',
  63536. 'menu': 'onSecondaryButtonStateChangedObservable',
  63537. 'grip': 'onMainButtonStateChangedObservable',
  63538. 'thumbstick': 'onPadStateChangedObservable',
  63539. 'trackpad': 'onTrackpadChangedObservable'
  63540. },
  63541. // A mapping of the axis name to glTF model node name
  63542. // that should be transformed by axis value.
  63543. // This array mirrors the browserGamepad.axes array, such that
  63544. // the mesh corresponding to axis 0 is in this array index 0.
  63545. axisMeshNames: [
  63546. 'THUMBSTICK_X',
  63547. 'THUMBSTICK_Y',
  63548. 'TOUCHPAD_TOUCH_X',
  63549. 'TOUCHPAD_TOUCH_Y'
  63550. ],
  63551. pointingPoseMeshName: 'POINTING_POSE'
  63552. };
  63553. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63554. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63555. _this.trackpad = { x: 0, y: 0 };
  63556. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63557. _this._loadedMeshInfo = null;
  63558. return _this;
  63559. }
  63560. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63561. get: function () {
  63562. return this.onTriggerStateChangedObservable;
  63563. },
  63564. enumerable: true,
  63565. configurable: true
  63566. });
  63567. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63568. get: function () {
  63569. return this.onSecondaryButtonStateChangedObservable;
  63570. },
  63571. enumerable: true,
  63572. configurable: true
  63573. });
  63574. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63575. get: function () {
  63576. return this.onMainButtonStateChangedObservable;
  63577. },
  63578. enumerable: true,
  63579. configurable: true
  63580. });
  63581. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63582. get: function () {
  63583. return this.onPadStateChangedObservable;
  63584. },
  63585. enumerable: true,
  63586. configurable: true
  63587. });
  63588. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63589. get: function () {
  63590. return this.onTrackpadChangedObservable;
  63591. },
  63592. enumerable: true,
  63593. configurable: true
  63594. });
  63595. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63596. get: function () {
  63597. return this.onTrackpadValuesChangedObservable;
  63598. },
  63599. enumerable: true,
  63600. configurable: true
  63601. });
  63602. /**
  63603. * Called once per frame by the engine.
  63604. */
  63605. WindowsMotionController.prototype.update = function () {
  63606. _super.prototype.update.call(this);
  63607. // Only need to animate axes if there is a loaded mesh
  63608. if (this._loadedMeshInfo) {
  63609. if (this.browserGamepad.axes) {
  63610. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63611. this.trackpad.x = this.browserGamepad["axes"][2];
  63612. this.trackpad.y = this.browserGamepad["axes"][3];
  63613. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63614. }
  63615. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63616. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63617. }
  63618. }
  63619. }
  63620. };
  63621. /**
  63622. * Called once for each button that changed state since the last frame
  63623. * @param buttonIdx Which button index changed
  63624. * @param state New state of the button
  63625. * @param changes Which properties on the state changed since last frame
  63626. */
  63627. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63628. var buttonName = this._mapping.buttons[buttonIdx];
  63629. if (!buttonName) {
  63630. return;
  63631. }
  63632. // Only emit events for buttons that we know how to map from index to name
  63633. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63634. if (observable) {
  63635. observable.notifyObservers(state);
  63636. }
  63637. this.lerpButtonTransform(buttonName, state.value);
  63638. };
  63639. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63640. // If there is no loaded mesh, there is nothing to transform.
  63641. if (!this._loadedMeshInfo) {
  63642. return;
  63643. }
  63644. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63645. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63646. return;
  63647. }
  63648. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63649. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63650. };
  63651. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63652. if (!this._loadedMeshInfo) {
  63653. return;
  63654. }
  63655. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63656. if (!meshInfo) {
  63657. return;
  63658. }
  63659. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63660. return;
  63661. }
  63662. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63663. var lerpValue = axisValue * 0.5 + 0.5;
  63664. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63665. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63666. };
  63667. /**
  63668. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63669. * @param scene scene in which to add meshes
  63670. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63671. */
  63672. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63673. var _this = this;
  63674. if (forceDefault === void 0) { forceDefault = false; }
  63675. var path;
  63676. var filename;
  63677. // Checking if GLB loader is present
  63678. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63679. // Determine the device specific folder based on the ID suffix
  63680. var device = 'default';
  63681. if (this.id && !forceDefault) {
  63682. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63683. device = ((match && match[0]) || device);
  63684. }
  63685. // Hand
  63686. if (this.hand === 'left') {
  63687. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63688. }
  63689. else {
  63690. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63691. }
  63692. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63693. }
  63694. else {
  63695. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63696. path = BABYLON.GenericController.MODEL_BASE_URL;
  63697. filename = BABYLON.GenericController.MODEL_FILENAME;
  63698. }
  63699. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63700. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63701. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63702. if (!_this._loadedMeshInfo) {
  63703. return;
  63704. }
  63705. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63706. _this.attachToMesh(_this._defaultModel);
  63707. if (meshLoaded) {
  63708. meshLoaded(_this._defaultModel);
  63709. }
  63710. }, null, function (scene, message) {
  63711. BABYLON.Tools.Log(message);
  63712. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63713. if (!forceDefault) {
  63714. _this.initControllerMesh(scene, meshLoaded, true);
  63715. }
  63716. });
  63717. };
  63718. /**
  63719. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63720. * can be transformed by button presses and axes values, based on this._mapping.
  63721. *
  63722. * @param scene scene in which the meshes exist
  63723. * @param meshes list of meshes that make up the controller model to process
  63724. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63725. */
  63726. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63727. var loadedMeshInfo = null;
  63728. // Create a new mesh to contain the glTF hierarchy
  63729. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63730. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63731. var childMesh = null;
  63732. for (var i = 0; i < meshes.length; i++) {
  63733. var mesh = meshes[i];
  63734. if (!mesh.parent) {
  63735. // Exclude controller meshes from picking results
  63736. mesh.isPickable = false;
  63737. // Handle root node, attach to the new parentMesh
  63738. childMesh = mesh;
  63739. break;
  63740. }
  63741. }
  63742. if (childMesh) {
  63743. childMesh.setParent(parentMesh);
  63744. // Create our mesh info. Note that this method will always return non-null.
  63745. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63746. }
  63747. else {
  63748. BABYLON.Tools.Warn('Could not find root node in model file.');
  63749. }
  63750. return loadedMeshInfo;
  63751. };
  63752. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63753. var loadedMeshInfo = new LoadedMeshInfo();
  63754. var i;
  63755. loadedMeshInfo.rootNode = rootNode;
  63756. // Reset the caches
  63757. loadedMeshInfo.buttonMeshes = {};
  63758. loadedMeshInfo.axisMeshes = {};
  63759. // Button Meshes
  63760. for (i = 0; i < this._mapping.buttons.length; i++) {
  63761. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63762. if (!buttonMeshName) {
  63763. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63764. continue;
  63765. }
  63766. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63767. if (!buttonMesh) {
  63768. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63769. continue;
  63770. }
  63771. var buttonMeshInfo = {
  63772. index: i,
  63773. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63774. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63775. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63776. };
  63777. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63778. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63779. }
  63780. else {
  63781. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63782. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63783. '(VALUE: ' + !!buttonMeshInfo.value +
  63784. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63785. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63786. ')');
  63787. }
  63788. }
  63789. // Axis Meshes
  63790. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63791. var axisMeshName = this._mapping.axisMeshNames[i];
  63792. if (!axisMeshName) {
  63793. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63794. continue;
  63795. }
  63796. var axisMesh = getChildByName(rootNode, axisMeshName);
  63797. if (!axisMesh) {
  63798. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63799. continue;
  63800. }
  63801. var axisMeshInfo = {
  63802. index: i,
  63803. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63804. min: getImmediateChildByName(axisMesh, 'MIN'),
  63805. max: getImmediateChildByName(axisMesh, 'MAX')
  63806. };
  63807. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63808. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63809. }
  63810. else {
  63811. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63812. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63813. '(VALUE: ' + !!axisMeshInfo.value +
  63814. ', MIN: ' + !!axisMeshInfo.min +
  63815. ', MAX:' + !!axisMeshInfo.max +
  63816. ')');
  63817. }
  63818. }
  63819. // Pointing Ray
  63820. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63821. if (!loadedMeshInfo.pointingPoseNode) {
  63822. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63823. }
  63824. return loadedMeshInfo;
  63825. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63826. function getChildByName(node, name) {
  63827. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63828. }
  63829. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63830. function getImmediateChildByName(node, name) {
  63831. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63832. }
  63833. };
  63834. WindowsMotionController.prototype.getForwardRay = function (length) {
  63835. if (length === void 0) { length = 100; }
  63836. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63837. return _super.prototype.getForwardRay.call(this, length);
  63838. }
  63839. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63840. var origin = m.getTranslation();
  63841. var forward = new BABYLON.Vector3(0, 0, -1);
  63842. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63843. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63844. return new BABYLON.Ray(origin, direction, length);
  63845. };
  63846. WindowsMotionController.prototype.dispose = function () {
  63847. _super.prototype.dispose.call(this);
  63848. this.onTrackpadChangedObservable.clear();
  63849. };
  63850. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63851. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63852. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63853. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63854. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63855. return WindowsMotionController;
  63856. }(BABYLON.WebVRController));
  63857. BABYLON.WindowsMotionController = WindowsMotionController;
  63858. })(BABYLON || (BABYLON = {}));
  63859. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63860. var BABYLON;
  63861. (function (BABYLON) {
  63862. var GearVRController = /** @class */ (function (_super) {
  63863. __extends(GearVRController, _super);
  63864. function GearVRController(vrGamepad) {
  63865. var _this = _super.call(this, vrGamepad) || this;
  63866. _this._buttonIndexToObservableNameMap = [
  63867. 'onTrackpadChangedObservable',
  63868. 'onTriggerStateChangedObservable' // Trigger
  63869. ];
  63870. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63871. return _this;
  63872. }
  63873. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63874. var _this = this;
  63875. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  63876. _this._defaultModel = newMeshes[1];
  63877. _this.attachToMesh(_this._defaultModel);
  63878. if (meshLoaded) {
  63879. meshLoaded(_this._defaultModel);
  63880. }
  63881. });
  63882. };
  63883. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63884. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  63885. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  63886. // Only emit events for buttons that we know how to map from index to observable
  63887. var observable = this[observableName];
  63888. if (observable) {
  63889. observable.notifyObservers(state);
  63890. }
  63891. }
  63892. };
  63893. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63894. GearVRController.MODEL_FILENAME = 'generic.babylon';
  63895. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  63896. return GearVRController;
  63897. }(BABYLON.WebVRController));
  63898. BABYLON.GearVRController = GearVRController;
  63899. })(BABYLON || (BABYLON = {}));
  63900. //# sourceMappingURL=babylon.gearVRController.js.map
  63901. var BABYLON;
  63902. (function (BABYLON) {
  63903. var FollowCamera = /** @class */ (function (_super) {
  63904. __extends(FollowCamera, _super);
  63905. function FollowCamera(name, position, scene, lockedTarget) {
  63906. if (lockedTarget === void 0) { lockedTarget = null; }
  63907. var _this = _super.call(this, name, position, scene) || this;
  63908. _this.radius = 12;
  63909. _this.rotationOffset = 0;
  63910. _this.heightOffset = 4;
  63911. _this.cameraAcceleration = 0.05;
  63912. _this.maxCameraSpeed = 20;
  63913. _this.lockedTarget = lockedTarget;
  63914. return _this;
  63915. }
  63916. FollowCamera.prototype.getRadians = function (degrees) {
  63917. return degrees * Math.PI / 180;
  63918. };
  63919. FollowCamera.prototype.follow = function (cameraTarget) {
  63920. if (!cameraTarget)
  63921. return;
  63922. var yRotation;
  63923. if (cameraTarget.rotationQuaternion) {
  63924. var rotMatrix = new BABYLON.Matrix();
  63925. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  63926. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  63927. }
  63928. else {
  63929. yRotation = cameraTarget.rotation.y;
  63930. }
  63931. var radians = this.getRadians(this.rotationOffset) + yRotation;
  63932. var targetPosition = cameraTarget.getAbsolutePosition();
  63933. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  63934. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  63935. var dx = targetX - this.position.x;
  63936. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  63937. var dz = (targetZ) - this.position.z;
  63938. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  63939. var vy = dy * this.cameraAcceleration;
  63940. var vz = dz * this.cameraAcceleration * 2;
  63941. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  63942. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63943. }
  63944. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  63945. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63946. }
  63947. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  63948. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63949. }
  63950. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  63951. this.setTarget(targetPosition);
  63952. };
  63953. FollowCamera.prototype._checkInputs = function () {
  63954. _super.prototype._checkInputs.call(this);
  63955. if (this.lockedTarget) {
  63956. this.follow(this.lockedTarget);
  63957. }
  63958. };
  63959. FollowCamera.prototype.getClassName = function () {
  63960. return "FollowCamera";
  63961. };
  63962. __decorate([
  63963. BABYLON.serialize()
  63964. ], FollowCamera.prototype, "radius", void 0);
  63965. __decorate([
  63966. BABYLON.serialize()
  63967. ], FollowCamera.prototype, "rotationOffset", void 0);
  63968. __decorate([
  63969. BABYLON.serialize()
  63970. ], FollowCamera.prototype, "heightOffset", void 0);
  63971. __decorate([
  63972. BABYLON.serialize()
  63973. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  63974. __decorate([
  63975. BABYLON.serialize()
  63976. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  63977. __decorate([
  63978. BABYLON.serializeAsMeshReference("lockedTargetId")
  63979. ], FollowCamera.prototype, "lockedTarget", void 0);
  63980. return FollowCamera;
  63981. }(BABYLON.TargetCamera));
  63982. BABYLON.FollowCamera = FollowCamera;
  63983. var ArcFollowCamera = /** @class */ (function (_super) {
  63984. __extends(ArcFollowCamera, _super);
  63985. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  63986. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  63987. _this.alpha = alpha;
  63988. _this.beta = beta;
  63989. _this.radius = radius;
  63990. _this.target = target;
  63991. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  63992. _this.follow();
  63993. return _this;
  63994. }
  63995. ArcFollowCamera.prototype.follow = function () {
  63996. if (!this.target) {
  63997. return;
  63998. }
  63999. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64000. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64001. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64002. var targetPosition = this.target.getAbsolutePosition();
  64003. this.position = targetPosition.add(this._cartesianCoordinates);
  64004. this.setTarget(targetPosition);
  64005. };
  64006. ArcFollowCamera.prototype._checkInputs = function () {
  64007. _super.prototype._checkInputs.call(this);
  64008. this.follow();
  64009. };
  64010. ArcFollowCamera.prototype.getClassName = function () {
  64011. return "ArcFollowCamera";
  64012. };
  64013. return ArcFollowCamera;
  64014. }(BABYLON.TargetCamera));
  64015. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64016. })(BABYLON || (BABYLON = {}));
  64017. //# sourceMappingURL=babylon.followCamera.js.map
  64018. var BABYLON;
  64019. (function (BABYLON) {
  64020. // We're mainly based on the logic defined into the FreeCamera code
  64021. var UniversalCamera = /** @class */ (function (_super) {
  64022. __extends(UniversalCamera, _super);
  64023. //-- end properties for backward compatibility for inputs
  64024. function UniversalCamera(name, position, scene) {
  64025. var _this = _super.call(this, name, position, scene) || this;
  64026. _this.inputs.addGamepad();
  64027. return _this;
  64028. }
  64029. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64030. //-- Begin properties for backward compatibility for inputs
  64031. get: function () {
  64032. var gamepad = this.inputs.attached["gamepad"];
  64033. if (gamepad)
  64034. return gamepad.gamepadAngularSensibility;
  64035. return 0;
  64036. },
  64037. set: function (value) {
  64038. var gamepad = this.inputs.attached["gamepad"];
  64039. if (gamepad)
  64040. gamepad.gamepadAngularSensibility = value;
  64041. },
  64042. enumerable: true,
  64043. configurable: true
  64044. });
  64045. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64046. get: function () {
  64047. var gamepad = this.inputs.attached["gamepad"];
  64048. if (gamepad)
  64049. return gamepad.gamepadMoveSensibility;
  64050. return 0;
  64051. },
  64052. set: function (value) {
  64053. var gamepad = this.inputs.attached["gamepad"];
  64054. if (gamepad)
  64055. gamepad.gamepadMoveSensibility = value;
  64056. },
  64057. enumerable: true,
  64058. configurable: true
  64059. });
  64060. UniversalCamera.prototype.getClassName = function () {
  64061. return "UniversalCamera";
  64062. };
  64063. return UniversalCamera;
  64064. }(BABYLON.TouchCamera));
  64065. BABYLON.UniversalCamera = UniversalCamera;
  64066. })(BABYLON || (BABYLON = {}));
  64067. //# sourceMappingURL=babylon.universalCamera.js.map
  64068. var BABYLON;
  64069. (function (BABYLON) {
  64070. // We're mainly based on the logic defined into the FreeCamera code
  64071. var GamepadCamera = /** @class */ (function (_super) {
  64072. __extends(GamepadCamera, _super);
  64073. //-- end properties for backward compatibility for inputs
  64074. function GamepadCamera(name, position, scene) {
  64075. return _super.call(this, name, position, scene) || this;
  64076. }
  64077. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64078. //-- Begin properties for backward compatibility for inputs
  64079. get: function () {
  64080. var gamepad = this.inputs.attached["gamepad"];
  64081. if (gamepad)
  64082. return gamepad.gamepadAngularSensibility;
  64083. return 0;
  64084. },
  64085. set: function (value) {
  64086. var gamepad = this.inputs.attached["gamepad"];
  64087. if (gamepad)
  64088. gamepad.gamepadAngularSensibility = value;
  64089. },
  64090. enumerable: true,
  64091. configurable: true
  64092. });
  64093. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64094. get: function () {
  64095. var gamepad = this.inputs.attached["gamepad"];
  64096. if (gamepad)
  64097. return gamepad.gamepadMoveSensibility;
  64098. return 0;
  64099. },
  64100. set: function (value) {
  64101. var gamepad = this.inputs.attached["gamepad"];
  64102. if (gamepad)
  64103. gamepad.gamepadMoveSensibility = value;
  64104. },
  64105. enumerable: true,
  64106. configurable: true
  64107. });
  64108. GamepadCamera.prototype.getClassName = function () {
  64109. return "GamepadCamera";
  64110. };
  64111. return GamepadCamera;
  64112. }(BABYLON.UniversalCamera));
  64113. BABYLON.GamepadCamera = GamepadCamera;
  64114. })(BABYLON || (BABYLON = {}));
  64115. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64116. var BABYLON;
  64117. (function (BABYLON) {
  64118. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64119. function PostProcessRenderPipelineManager() {
  64120. this._renderPipelines = {};
  64121. }
  64122. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64123. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64124. };
  64125. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64126. if (unique === void 0) { unique = false; }
  64127. var renderPipeline = this._renderPipelines[renderPipelineName];
  64128. if (!renderPipeline) {
  64129. return;
  64130. }
  64131. renderPipeline._attachCameras(cameras, unique);
  64132. };
  64133. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64134. var renderPipeline = this._renderPipelines[renderPipelineName];
  64135. if (!renderPipeline) {
  64136. return;
  64137. }
  64138. renderPipeline._detachCameras(cameras);
  64139. };
  64140. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64141. var renderPipeline = this._renderPipelines[renderPipelineName];
  64142. if (!renderPipeline) {
  64143. return;
  64144. }
  64145. renderPipeline._enableEffect(renderEffectName, cameras);
  64146. };
  64147. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64148. var renderPipeline = this._renderPipelines[renderPipelineName];
  64149. if (!renderPipeline) {
  64150. return;
  64151. }
  64152. renderPipeline._disableEffect(renderEffectName, cameras);
  64153. };
  64154. PostProcessRenderPipelineManager.prototype.update = function () {
  64155. for (var renderPipelineName in this._renderPipelines) {
  64156. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64157. var pipeline = this._renderPipelines[renderPipelineName];
  64158. if (!pipeline.isSupported) {
  64159. pipeline.dispose();
  64160. delete this._renderPipelines[renderPipelineName];
  64161. }
  64162. else {
  64163. pipeline._update();
  64164. }
  64165. }
  64166. }
  64167. };
  64168. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64169. for (var renderPipelineName in this._renderPipelines) {
  64170. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64171. var pipeline = this._renderPipelines[renderPipelineName];
  64172. pipeline._rebuild();
  64173. }
  64174. }
  64175. };
  64176. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64177. for (var renderPipelineName in this._renderPipelines) {
  64178. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64179. var pipeline = this._renderPipelines[renderPipelineName];
  64180. pipeline.dispose();
  64181. }
  64182. }
  64183. };
  64184. return PostProcessRenderPipelineManager;
  64185. }());
  64186. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64187. })(BABYLON || (BABYLON = {}));
  64188. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64189. var BABYLON;
  64190. (function (BABYLON) {
  64191. /**
  64192. * This represents a set of one or more post processes in Babylon.
  64193. * A post process can be used to apply a shader to a texture after it is rendered.
  64194. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64195. */
  64196. var PostProcessRenderEffect = /** @class */ (function () {
  64197. /**
  64198. * Instantiates a post process render effect.
  64199. * A post process can be used to apply a shader to a texture after it is rendered.
  64200. * @param engine The engine the effect is tied to
  64201. * @param name The name of the effect
  64202. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64203. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64204. */
  64205. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64206. this._name = name;
  64207. this._singleInstance = singleInstance || true;
  64208. this._getPostProcesses = getPostProcesses;
  64209. this._cameras = {};
  64210. this._indicesForCamera = {};
  64211. this._postProcesses = {};
  64212. }
  64213. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64214. /**
  64215. * Checks if all the post processes in the effect are supported.
  64216. */
  64217. get: function () {
  64218. for (var index in this._postProcesses) {
  64219. for (var ppIndex in this._postProcesses[index]) {
  64220. if (!this._postProcesses[index][ppIndex].isSupported) {
  64221. return false;
  64222. }
  64223. }
  64224. }
  64225. return true;
  64226. },
  64227. enumerable: true,
  64228. configurable: true
  64229. });
  64230. /**
  64231. * Updates the current state of the effect
  64232. */
  64233. PostProcessRenderEffect.prototype._update = function () {
  64234. };
  64235. /**
  64236. * Attaches the effect on cameras
  64237. * @param cameras The camera to attach to.
  64238. */
  64239. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64240. var _this = this;
  64241. var cameraKey;
  64242. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64243. if (!cams) {
  64244. return;
  64245. }
  64246. for (var i = 0; i < cams.length; i++) {
  64247. var camera = cams[i];
  64248. var cameraName = camera.name;
  64249. if (this._singleInstance) {
  64250. cameraKey = 0;
  64251. }
  64252. else {
  64253. cameraKey = cameraName;
  64254. }
  64255. if (!this._postProcesses[cameraKey]) {
  64256. var postProcess = this._getPostProcesses();
  64257. if (postProcess) {
  64258. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64259. }
  64260. }
  64261. if (!this._indicesForCamera[cameraName]) {
  64262. this._indicesForCamera[cameraName] = [];
  64263. }
  64264. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64265. var index = camera.attachPostProcess(postProcess);
  64266. _this._indicesForCamera[cameraName].push(index);
  64267. });
  64268. if (!this._cameras[cameraName]) {
  64269. this._cameras[cameraName] = camera;
  64270. }
  64271. }
  64272. };
  64273. /**
  64274. * Detatches the effect on cameras
  64275. * @param cameras The camera to detatch from.
  64276. */
  64277. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64278. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64279. if (!cams) {
  64280. return;
  64281. }
  64282. for (var i = 0; i < cams.length; i++) {
  64283. var camera = cams[i];
  64284. var cameraName = camera.name;
  64285. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64286. camera.detachPostProcess(postProcess);
  64287. });
  64288. if (this._cameras[cameraName]) {
  64289. //this._indicesForCamera.splice(index, 1);
  64290. this._cameras[cameraName] = null;
  64291. }
  64292. }
  64293. };
  64294. /**
  64295. * Enables the effect on given cameras
  64296. * @param cameras The camera to enable.
  64297. */
  64298. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64299. var _this = this;
  64300. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64301. if (!cams) {
  64302. return;
  64303. }
  64304. for (var i = 0; i < cams.length; i++) {
  64305. var camera = cams[i];
  64306. var cameraName = camera.name;
  64307. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64308. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64309. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64310. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64311. });
  64312. }
  64313. }
  64314. }
  64315. };
  64316. /**
  64317. * Disables the effect on the given cameras
  64318. * @param cameras The camera to disable.
  64319. */
  64320. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64321. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64322. if (!cams) {
  64323. return;
  64324. }
  64325. for (var i = 0; i < cams.length; i++) {
  64326. var camera = cams[i];
  64327. var cameraName = camera.name;
  64328. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64329. camera.detachPostProcess(postProcess);
  64330. });
  64331. }
  64332. };
  64333. /**
  64334. * Gets a list of the post processes contained in the effect.
  64335. * @param camera The camera to get the post processes on.
  64336. * @returns The list of the post processes in the effect.
  64337. */
  64338. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64339. if (this._singleInstance) {
  64340. return this._postProcesses[0];
  64341. }
  64342. else {
  64343. if (!camera) {
  64344. return null;
  64345. }
  64346. return this._postProcesses[camera.name];
  64347. }
  64348. };
  64349. return PostProcessRenderEffect;
  64350. }());
  64351. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64352. })(BABYLON || (BABYLON = {}));
  64353. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64354. var BABYLON;
  64355. (function (BABYLON) {
  64356. var PostProcessRenderPipeline = /** @class */ (function () {
  64357. function PostProcessRenderPipeline(engine, name) {
  64358. this._name = name;
  64359. this._renderEffects = {};
  64360. this._renderEffectsForIsolatedPass = new Array();
  64361. this._cameras = [];
  64362. }
  64363. PostProcessRenderPipeline.prototype.getClassName = function () {
  64364. return "PostProcessRenderPipeline";
  64365. };
  64366. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64367. get: function () {
  64368. for (var renderEffectName in this._renderEffects) {
  64369. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64370. if (!this._renderEffects[renderEffectName].isSupported) {
  64371. return false;
  64372. }
  64373. }
  64374. }
  64375. return true;
  64376. },
  64377. enumerable: true,
  64378. configurable: true
  64379. });
  64380. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64381. this._renderEffects[renderEffect._name] = renderEffect;
  64382. };
  64383. // private
  64384. PostProcessRenderPipeline.prototype._rebuild = function () {
  64385. };
  64386. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64387. var renderEffects = this._renderEffects[renderEffectName];
  64388. if (!renderEffects) {
  64389. return;
  64390. }
  64391. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64392. };
  64393. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64394. var renderEffects = this._renderEffects[renderEffectName];
  64395. if (!renderEffects) {
  64396. return;
  64397. }
  64398. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64399. };
  64400. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64401. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64402. if (!cams) {
  64403. return;
  64404. }
  64405. var indicesToDelete = [];
  64406. var i;
  64407. for (i = 0; i < cams.length; i++) {
  64408. var camera = cams[i];
  64409. var cameraName = camera.name;
  64410. if (this._cameras.indexOf(camera) === -1) {
  64411. this._cameras[cameraName] = camera;
  64412. }
  64413. else if (unique) {
  64414. indicesToDelete.push(i);
  64415. }
  64416. }
  64417. for (i = 0; i < indicesToDelete.length; i++) {
  64418. cameras.splice(indicesToDelete[i], 1);
  64419. }
  64420. for (var renderEffectName in this._renderEffects) {
  64421. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64422. this._renderEffects[renderEffectName]._attachCameras(cams);
  64423. }
  64424. }
  64425. };
  64426. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64427. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64428. if (!cams) {
  64429. return;
  64430. }
  64431. for (var renderEffectName in this._renderEffects) {
  64432. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64433. this._renderEffects[renderEffectName]._detachCameras(cams);
  64434. }
  64435. }
  64436. for (var i = 0; i < cams.length; i++) {
  64437. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64438. }
  64439. };
  64440. PostProcessRenderPipeline.prototype._update = function () {
  64441. for (var renderEffectName in this._renderEffects) {
  64442. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64443. this._renderEffects[renderEffectName]._update();
  64444. }
  64445. }
  64446. for (var i = 0; i < this._cameras.length; i++) {
  64447. var cameraName = this._cameras[i].name;
  64448. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64449. this._renderEffectsForIsolatedPass[cameraName]._update();
  64450. }
  64451. }
  64452. };
  64453. PostProcessRenderPipeline.prototype._reset = function () {
  64454. this._renderEffects = {};
  64455. this._renderEffectsForIsolatedPass = new Array();
  64456. };
  64457. PostProcessRenderPipeline.prototype.dispose = function () {
  64458. // Must be implemented by children
  64459. };
  64460. __decorate([
  64461. BABYLON.serialize()
  64462. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64463. return PostProcessRenderPipeline;
  64464. }());
  64465. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64466. })(BABYLON || (BABYLON = {}));
  64467. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64468. var BABYLON;
  64469. (function (BABYLON) {
  64470. var DepthRenderer = /** @class */ (function () {
  64471. function DepthRenderer(scene, type) {
  64472. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64473. var _this = this;
  64474. this._scene = scene;
  64475. var engine = scene.getEngine();
  64476. // Render target
  64477. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64478. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64479. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64480. this._depthMap.refreshRate = 1;
  64481. this._depthMap.renderParticles = false;
  64482. this._depthMap.renderList = null;
  64483. // set default depth value to 1.0 (far away)
  64484. this._depthMap.onClearObservable.add(function (engine) {
  64485. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64486. });
  64487. // Custom render function
  64488. var renderSubMesh = function (subMesh) {
  64489. var mesh = subMesh.getRenderingMesh();
  64490. var scene = _this._scene;
  64491. var engine = scene.getEngine();
  64492. var material = subMesh.getMaterial();
  64493. if (!material) {
  64494. return;
  64495. }
  64496. // Culling and reverse (right handed system)
  64497. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64498. // Managing instances
  64499. var batch = mesh._getInstancesRenderList(subMesh._id);
  64500. if (batch.mustReturn) {
  64501. return;
  64502. }
  64503. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64504. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64505. engine.enableEffect(_this._effect);
  64506. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64507. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64508. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64509. // Alpha test
  64510. if (material && material.needAlphaTesting()) {
  64511. var alphaTexture = material.getAlphaTestTexture();
  64512. if (alphaTexture) {
  64513. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64514. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64515. }
  64516. }
  64517. // Bones
  64518. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64519. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64520. }
  64521. // Draw
  64522. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64523. }
  64524. };
  64525. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64526. var index;
  64527. if (depthOnlySubMeshes.length) {
  64528. engine.setColorWrite(false);
  64529. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64530. renderSubMesh(depthOnlySubMeshes.data[index]);
  64531. }
  64532. engine.setColorWrite(true);
  64533. }
  64534. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64535. renderSubMesh(opaqueSubMeshes.data[index]);
  64536. }
  64537. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64538. renderSubMesh(alphaTestSubMeshes.data[index]);
  64539. }
  64540. };
  64541. }
  64542. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64543. var material = subMesh.getMaterial();
  64544. if (material.disableDepthWrite) {
  64545. return false;
  64546. }
  64547. var defines = [];
  64548. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64549. var mesh = subMesh.getMesh();
  64550. // Alpha test
  64551. if (material && material.needAlphaTesting()) {
  64552. defines.push("#define ALPHATEST");
  64553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64554. attribs.push(BABYLON.VertexBuffer.UVKind);
  64555. defines.push("#define UV1");
  64556. }
  64557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64558. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64559. defines.push("#define UV2");
  64560. }
  64561. }
  64562. // Bones
  64563. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64566. if (mesh.numBoneInfluencers > 4) {
  64567. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64568. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64569. }
  64570. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64571. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64572. }
  64573. else {
  64574. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64575. }
  64576. // Instances
  64577. if (useInstances) {
  64578. defines.push("#define INSTANCES");
  64579. attribs.push("world0");
  64580. attribs.push("world1");
  64581. attribs.push("world2");
  64582. attribs.push("world3");
  64583. }
  64584. // Get correct effect
  64585. var join = defines.join("\n");
  64586. if (this._cachedDefines !== join) {
  64587. this._cachedDefines = join;
  64588. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64589. }
  64590. return this._effect.isReady();
  64591. };
  64592. DepthRenderer.prototype.getDepthMap = function () {
  64593. return this._depthMap;
  64594. };
  64595. // Methods
  64596. DepthRenderer.prototype.dispose = function () {
  64597. this._depthMap.dispose();
  64598. };
  64599. return DepthRenderer;
  64600. }());
  64601. BABYLON.DepthRenderer = DepthRenderer;
  64602. })(BABYLON || (BABYLON = {}));
  64603. //# sourceMappingURL=babylon.depthRenderer.js.map
  64604. var BABYLON;
  64605. (function (BABYLON) {
  64606. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64607. __extends(SSAORenderingPipeline, _super);
  64608. /**
  64609. * @constructor
  64610. * @param {string} name - The rendering pipeline name
  64611. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64612. * @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 }
  64613. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64614. */
  64615. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64616. var _this = _super.call(this, scene.getEngine(), name) || this;
  64617. // Members
  64618. /**
  64619. * The PassPostProcess id in the pipeline that contains the original scene color
  64620. * @type {string}
  64621. */
  64622. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64623. /**
  64624. * The SSAO PostProcess id in the pipeline
  64625. * @type {string}
  64626. */
  64627. _this.SSAORenderEffect = "SSAORenderEffect";
  64628. /**
  64629. * The horizontal blur PostProcess id in the pipeline
  64630. * @type {string}
  64631. */
  64632. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64633. /**
  64634. * The vertical blur PostProcess id in the pipeline
  64635. * @type {string}
  64636. */
  64637. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64638. /**
  64639. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64640. * @type {string}
  64641. */
  64642. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64643. /**
  64644. * The output strength of the SSAO post-process. Default value is 1.0.
  64645. * @type {number}
  64646. */
  64647. _this.totalStrength = 1.0;
  64648. /**
  64649. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64650. * @type {number}
  64651. */
  64652. _this.radius = 0.0001;
  64653. /**
  64654. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64655. * Must not be equal to fallOff and superior to fallOff.
  64656. * Default value is 0.975
  64657. * @type {number}
  64658. */
  64659. _this.area = 0.0075;
  64660. /**
  64661. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64662. * Must not be equal to area and inferior to area.
  64663. * Default value is 0.0
  64664. * @type {number}
  64665. */
  64666. _this.fallOff = 0.000001;
  64667. /**
  64668. * The base color of the SSAO post-process
  64669. * The final result is "base + ssao" between [0, 1]
  64670. * @type {number}
  64671. */
  64672. _this.base = 0.5;
  64673. _this._firstUpdate = true;
  64674. _this._scene = scene;
  64675. // Set up assets
  64676. _this._createRandomTexture();
  64677. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64678. var ssaoRatio = ratio.ssaoRatio || ratio;
  64679. var combineRatio = ratio.combineRatio || ratio;
  64680. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64681. _this._createSSAOPostProcess(ssaoRatio);
  64682. _this._createBlurPostProcess(ssaoRatio);
  64683. _this._createSSAOCombinePostProcess(combineRatio);
  64684. // Set up pipeline
  64685. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64686. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64687. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64688. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64690. // Finish
  64691. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64692. if (cameras)
  64693. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64694. return _this;
  64695. }
  64696. // Public Methods
  64697. /**
  64698. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64699. */
  64700. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64701. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64702. for (var i = 0; i < this._scene.cameras.length; i++) {
  64703. var camera = this._scene.cameras[i];
  64704. this._originalColorPostProcess.dispose(camera);
  64705. this._ssaoPostProcess.dispose(camera);
  64706. this._blurHPostProcess.dispose(camera);
  64707. this._blurVPostProcess.dispose(camera);
  64708. this._ssaoCombinePostProcess.dispose(camera);
  64709. }
  64710. this._randomTexture.dispose();
  64711. if (disableDepthRender)
  64712. this._scene.disableDepthRenderer();
  64713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64714. _super.prototype.dispose.call(this);
  64715. };
  64716. // Private Methods
  64717. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64718. var _this = this;
  64719. var size = 16;
  64720. 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);
  64721. 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);
  64722. this._blurHPostProcess.onActivateObservable.add(function () {
  64723. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64724. _this._blurHPostProcess.kernel = size * dw;
  64725. });
  64726. this._blurVPostProcess.onActivateObservable.add(function () {
  64727. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64728. _this._blurVPostProcess.kernel = size * dw;
  64729. });
  64730. };
  64731. SSAORenderingPipeline.prototype._rebuild = function () {
  64732. this._firstUpdate = true;
  64733. _super.prototype._rebuild.call(this);
  64734. };
  64735. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64736. var _this = this;
  64737. var numSamples = 16;
  64738. var sampleSphere = [
  64739. 0.5381, 0.1856, -0.4319,
  64740. 0.1379, 0.2486, 0.4430,
  64741. 0.3371, 0.5679, -0.0057,
  64742. -0.6999, -0.0451, -0.0019,
  64743. 0.0689, -0.1598, -0.8547,
  64744. 0.0560, 0.0069, -0.1843,
  64745. -0.0146, 0.1402, 0.0762,
  64746. 0.0100, -0.1924, -0.0344,
  64747. -0.3577, -0.5301, -0.4358,
  64748. -0.3169, 0.1063, 0.0158,
  64749. 0.0103, -0.5869, 0.0046,
  64750. -0.0897, -0.4940, 0.3287,
  64751. 0.7119, -0.0154, -0.0918,
  64752. -0.0533, 0.0596, -0.5411,
  64753. 0.0352, -0.0631, 0.5460,
  64754. -0.4776, 0.2847, -0.0271
  64755. ];
  64756. var samplesFactor = 1.0 / numSamples;
  64757. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64758. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64759. "area", "fallOff", "base", "range", "viewport"
  64760. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64761. this._ssaoPostProcess.onApply = function (effect) {
  64762. if (_this._firstUpdate) {
  64763. effect.setArray3("sampleSphere", sampleSphere);
  64764. effect.setFloat("samplesFactor", samplesFactor);
  64765. effect.setFloat("randTextureTiles", 4.0);
  64766. }
  64767. effect.setFloat("totalStrength", _this.totalStrength);
  64768. effect.setFloat("radius", _this.radius);
  64769. effect.setFloat("area", _this.area);
  64770. effect.setFloat("fallOff", _this.fallOff);
  64771. effect.setFloat("base", _this.base);
  64772. effect.setTexture("textureSampler", _this._depthTexture);
  64773. effect.setTexture("randomSampler", _this._randomTexture);
  64774. };
  64775. };
  64776. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64777. var _this = this;
  64778. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64779. this._ssaoCombinePostProcess.onApply = function (effect) {
  64780. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64781. };
  64782. };
  64783. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64784. var size = 512;
  64785. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64786. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64787. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64788. var context = this._randomTexture.getContext();
  64789. var rand = function (min, max) {
  64790. return Math.random() * (max - min) + min;
  64791. };
  64792. var randVector = BABYLON.Vector3.Zero();
  64793. for (var x = 0; x < size; x++) {
  64794. for (var y = 0; y < size; y++) {
  64795. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64796. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64797. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64798. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64799. context.fillRect(x, y, 1, 1);
  64800. }
  64801. }
  64802. this._randomTexture.update(false);
  64803. };
  64804. __decorate([
  64805. BABYLON.serialize()
  64806. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64807. __decorate([
  64808. BABYLON.serialize()
  64809. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64810. __decorate([
  64811. BABYLON.serialize()
  64812. ], SSAORenderingPipeline.prototype, "area", void 0);
  64813. __decorate([
  64814. BABYLON.serialize()
  64815. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64816. __decorate([
  64817. BABYLON.serialize()
  64818. ], SSAORenderingPipeline.prototype, "base", void 0);
  64819. return SSAORenderingPipeline;
  64820. }(BABYLON.PostProcessRenderPipeline));
  64821. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64822. })(BABYLON || (BABYLON = {}));
  64823. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64824. var BABYLON;
  64825. (function (BABYLON) {
  64826. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64827. __extends(SSAO2RenderingPipeline, _super);
  64828. /**
  64829. * @constructor
  64830. * @param {string} name - The rendering pipeline name
  64831. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64832. * @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 }
  64833. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64834. */
  64835. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64836. var _this = _super.call(this, scene.getEngine(), name) || this;
  64837. // Members
  64838. /**
  64839. * The PassPostProcess id in the pipeline that contains the original scene color
  64840. * @type {string}
  64841. */
  64842. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64843. /**
  64844. * The SSAO PostProcess id in the pipeline
  64845. * @type {string}
  64846. */
  64847. _this.SSAORenderEffect = "SSAORenderEffect";
  64848. /**
  64849. * The horizontal blur PostProcess id in the pipeline
  64850. * @type {string}
  64851. */
  64852. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64853. /**
  64854. * The vertical blur PostProcess id in the pipeline
  64855. * @type {string}
  64856. */
  64857. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64858. /**
  64859. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64860. * @type {string}
  64861. */
  64862. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64863. /**
  64864. * The output strength of the SSAO post-process. Default value is 1.0.
  64865. * @type {number}
  64866. */
  64867. _this.totalStrength = 1.0;
  64868. /**
  64869. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64870. * @type {number}
  64871. */
  64872. _this.maxZ = 100.0;
  64873. /**
  64874. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64875. * @type {number}
  64876. */
  64877. _this.minZAspect = 0.2;
  64878. /**
  64879. * Number of samples used for the SSAO calculations. Default value is 8
  64880. * @type {number}
  64881. */
  64882. _this._samples = 8;
  64883. /**
  64884. * Are we using bilateral blur ?
  64885. * @type {boolean}
  64886. */
  64887. _this._expensiveBlur = true;
  64888. /**
  64889. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  64890. * @type {number}
  64891. */
  64892. _this.radius = 2.0;
  64893. /**
  64894. * The base color of the SSAO post-process
  64895. * The final result is "base + ssao" between [0, 1]
  64896. * @type {number}
  64897. */
  64898. _this.base = 0.1;
  64899. _this._firstUpdate = true;
  64900. _this._scene = scene;
  64901. if (!_this.isSupported) {
  64902. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  64903. return _this;
  64904. }
  64905. var ssaoRatio = ratio.ssaoRatio || ratio;
  64906. var blurRatio = ratio.blurRatio || ratio;
  64907. // Set up assets
  64908. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  64909. _this._createRandomTexture();
  64910. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  64911. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  64912. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64913. _this._createSSAOPostProcess(1.0);
  64914. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  64915. _this._createSSAOCombinePostProcess(blurRatio);
  64916. // Set up pipeline
  64917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64920. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64921. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64922. // Finish
  64923. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64924. if (cameras)
  64925. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64926. return _this;
  64927. }
  64928. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  64929. get: function () {
  64930. return this._samples;
  64931. },
  64932. set: function (n) {
  64933. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  64934. this._samples = n;
  64935. this._sampleSphere = this._generateHemisphere();
  64936. this._firstUpdate = true;
  64937. },
  64938. enumerable: true,
  64939. configurable: true
  64940. });
  64941. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  64942. get: function () {
  64943. return this._expensiveBlur;
  64944. },
  64945. set: function (b) {
  64946. 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"]);
  64947. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  64948. this._expensiveBlur = b;
  64949. this._firstUpdate = true;
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  64955. /**
  64956. * Support test.
  64957. * @type {boolean}
  64958. */
  64959. get: function () {
  64960. var engine = BABYLON.Engine.LastCreatedEngine;
  64961. if (!engine) {
  64962. return false;
  64963. }
  64964. return engine.getCaps().drawBuffersExtension;
  64965. },
  64966. enumerable: true,
  64967. configurable: true
  64968. });
  64969. // Public Methods
  64970. /**
  64971. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64972. */
  64973. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  64974. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  64975. for (var i = 0; i < this._scene.cameras.length; i++) {
  64976. var camera = this._scene.cameras[i];
  64977. this._originalColorPostProcess.dispose(camera);
  64978. this._ssaoPostProcess.dispose(camera);
  64979. this._blurHPostProcess.dispose(camera);
  64980. this._blurVPostProcess.dispose(camera);
  64981. this._ssaoCombinePostProcess.dispose(camera);
  64982. }
  64983. this._randomTexture.dispose();
  64984. if (disableGeometryBufferRenderer)
  64985. this._scene.disableGeometryBufferRenderer();
  64986. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64987. _super.prototype.dispose.call(this);
  64988. };
  64989. // Private Methods
  64990. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  64991. var _this = this;
  64992. this._samplerOffsets = [];
  64993. var expensive = this.expensiveBlur;
  64994. for (var i = -8; i < 8; i++) {
  64995. this._samplerOffsets.push(i * 2 + 0.5);
  64996. }
  64997. 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");
  64998. this._blurHPostProcess.onApply = function (effect) {
  64999. if (!_this._scene.activeCamera) {
  65000. return;
  65001. }
  65002. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65003. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65004. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65005. effect.setFloat("radius", _this.radius);
  65006. effect.setTexture("depthSampler", _this._depthTexture);
  65007. if (_this._firstUpdate) {
  65008. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65009. }
  65010. };
  65011. 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");
  65012. this._blurVPostProcess.onApply = function (effect) {
  65013. if (!_this._scene.activeCamera) {
  65014. return;
  65015. }
  65016. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65017. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65018. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65019. effect.setFloat("radius", _this.radius);
  65020. effect.setTexture("depthSampler", _this._depthTexture);
  65021. if (_this._firstUpdate) {
  65022. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65023. _this._firstUpdate = false;
  65024. }
  65025. };
  65026. };
  65027. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65028. this._firstUpdate = true;
  65029. _super.prototype._rebuild.call(this);
  65030. };
  65031. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65032. var numSamples = this.samples;
  65033. var result = [];
  65034. var vector, scale;
  65035. var rand = function (min, max) {
  65036. return Math.random() * (max - min) + min;
  65037. };
  65038. var i = 0;
  65039. while (i < numSamples) {
  65040. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65041. vector.normalize();
  65042. scale = i / numSamples;
  65043. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65044. vector.scaleInPlace(scale);
  65045. result.push(vector.x, vector.y, vector.z);
  65046. i++;
  65047. }
  65048. return result;
  65049. };
  65050. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65051. var _this = this;
  65052. var numSamples = this.samples;
  65053. this._sampleSphere = this._generateHemisphere();
  65054. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65055. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65056. "base", "range", "projection", "near", "far", "texelSize",
  65057. "xViewport", "yViewport", "maxZ", "minZAspect"
  65058. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65059. this._ssaoPostProcess.onApply = function (effect) {
  65060. if (_this._firstUpdate) {
  65061. effect.setArray3("sampleSphere", _this._sampleSphere);
  65062. effect.setFloat("randTextureTiles", 4.0);
  65063. }
  65064. if (!_this._scene.activeCamera) {
  65065. return;
  65066. }
  65067. effect.setFloat("samplesFactor", 1 / _this.samples);
  65068. effect.setFloat("totalStrength", _this.totalStrength);
  65069. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65070. effect.setFloat("radius", _this.radius);
  65071. effect.setFloat("maxZ", _this.maxZ);
  65072. effect.setFloat("minZAspect", _this.minZAspect);
  65073. effect.setFloat("base", _this.base);
  65074. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65075. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65076. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65077. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65078. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65079. effect.setTexture("textureSampler", _this._depthTexture);
  65080. effect.setTexture("normalSampler", _this._normalTexture);
  65081. effect.setTexture("randomSampler", _this._randomTexture);
  65082. };
  65083. };
  65084. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65085. var _this = this;
  65086. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65087. this._ssaoCombinePostProcess.onApply = function (effect) {
  65088. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65089. };
  65090. };
  65091. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65092. var size = 512;
  65093. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65094. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65095. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65096. var context = this._randomTexture.getContext();
  65097. var rand = function (min, max) {
  65098. return Math.random() * (max - min) + min;
  65099. };
  65100. var randVector = BABYLON.Vector3.Zero();
  65101. for (var x = 0; x < size; x++) {
  65102. for (var y = 0; y < size; y++) {
  65103. randVector.x = rand(0.0, 1.0);
  65104. randVector.y = rand(0.0, 1.0);
  65105. randVector.z = 0.0;
  65106. randVector.normalize();
  65107. randVector.scaleInPlace(255);
  65108. randVector.x = Math.floor(randVector.x);
  65109. randVector.y = Math.floor(randVector.y);
  65110. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65111. context.fillRect(x, y, 1, 1);
  65112. }
  65113. }
  65114. this._randomTexture.update(false);
  65115. };
  65116. __decorate([
  65117. BABYLON.serialize()
  65118. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65119. __decorate([
  65120. BABYLON.serialize()
  65121. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65122. __decorate([
  65123. BABYLON.serialize()
  65124. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65125. __decorate([
  65126. BABYLON.serialize("samples")
  65127. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65128. __decorate([
  65129. BABYLON.serialize("expensiveBlur")
  65130. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65131. __decorate([
  65132. BABYLON.serialize()
  65133. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65134. __decorate([
  65135. BABYLON.serialize()
  65136. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65137. return SSAO2RenderingPipeline;
  65138. }(BABYLON.PostProcessRenderPipeline));
  65139. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65140. })(BABYLON || (BABYLON = {}));
  65141. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65142. // BABYLON.JS Chromatic Aberration GLSL Shader
  65143. // Author: Olivier Guyot
  65144. // Separates very slightly R, G and B colors on the edges of the screen
  65145. // Inspired by Francois Tarlier & Martins Upitis
  65146. var BABYLON;
  65147. (function (BABYLON) {
  65148. var LensRenderingPipeline = /** @class */ (function (_super) {
  65149. __extends(LensRenderingPipeline, _super);
  65150. /**
  65151. * @constructor
  65152. *
  65153. * Effect parameters are as follow:
  65154. * {
  65155. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65156. * edge_blur: number; // from 0 to x (1 for realism)
  65157. * distortion: number; // from 0 to x (1 for realism)
  65158. * grain_amount: number; // from 0 to 1
  65159. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65160. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65161. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65162. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65163. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65164. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65165. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65166. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65167. * }
  65168. * Note: if an effect parameter is unset, effect is disabled
  65169. *
  65170. * @param {string} name - The rendering pipeline name
  65171. * @param {object} parameters - An object containing all parameters (see above)
  65172. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65173. * @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)
  65174. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65175. */
  65176. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65177. if (ratio === void 0) { ratio = 1.0; }
  65178. var _this = _super.call(this, scene.getEngine(), name) || this;
  65179. // Lens effects can be of the following:
  65180. // - chromatic aberration (slight shift of RGB colors)
  65181. // - blur on the edge of the lens
  65182. // - lens distortion
  65183. // - depth-of-field blur & highlights enhancing
  65184. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65185. // - grain effect (noise or custom texture)
  65186. // Two additional texture samplers are needed:
  65187. // - depth map (for depth-of-field)
  65188. // - grain texture
  65189. /**
  65190. * The chromatic aberration PostProcess id in the pipeline
  65191. * @type {string}
  65192. */
  65193. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65194. /**
  65195. * The highlights enhancing PostProcess id in the pipeline
  65196. * @type {string}
  65197. */
  65198. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65199. /**
  65200. * The depth-of-field PostProcess id in the pipeline
  65201. * @type {string}
  65202. */
  65203. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65204. _this._scene = scene;
  65205. // Fetch texture samplers
  65206. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65207. if (parameters.grain_texture) {
  65208. _this._grainTexture = parameters.grain_texture;
  65209. }
  65210. else {
  65211. _this._createGrainTexture();
  65212. }
  65213. // save parameters
  65214. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65215. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65216. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65217. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65218. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65219. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65220. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65221. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65222. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65223. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65224. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65225. // Create effects
  65226. _this._createChromaticAberrationPostProcess(ratio);
  65227. _this._createHighlightsPostProcess(ratio);
  65228. _this._createDepthOfFieldPostProcess(ratio / 4);
  65229. // Set up pipeline
  65230. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65231. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65232. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65233. if (_this._highlightsGain === -1) {
  65234. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65235. }
  65236. // Finish
  65237. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65238. if (cameras) {
  65239. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65240. }
  65241. return _this;
  65242. }
  65243. // public methods (self explanatory)
  65244. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65245. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65246. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65247. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65248. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65249. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65250. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65251. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65252. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65253. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65254. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65255. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65256. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65257. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65258. };
  65259. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65260. this._highlightsPostProcess.updateEffect();
  65261. };
  65262. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65263. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65264. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65265. this._highlightsGain = amount;
  65266. };
  65267. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65268. if (this._highlightsGain === -1) {
  65269. this._highlightsGain = 1.0;
  65270. }
  65271. this._highlightsThreshold = amount;
  65272. };
  65273. LensRenderingPipeline.prototype.disableHighlights = function () {
  65274. this._highlightsGain = -1;
  65275. };
  65276. /**
  65277. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65278. */
  65279. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65280. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65281. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65282. this._chromaticAberrationPostProcess = null;
  65283. this._highlightsPostProcess = null;
  65284. this._depthOfFieldPostProcess = null;
  65285. this._grainTexture.dispose();
  65286. if (disableDepthRender)
  65287. this._scene.disableDepthRenderer();
  65288. };
  65289. // colors shifting and distortion
  65290. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65291. var _this = this;
  65292. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65293. [], // samplers
  65294. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65295. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65296. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65297. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65298. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65299. };
  65300. };
  65301. // highlights enhancing
  65302. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65303. var _this = this;
  65304. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65305. [], // samplers
  65306. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65307. this._highlightsPostProcess.onApply = function (effect) {
  65308. effect.setFloat('gain', _this._highlightsGain);
  65309. effect.setFloat('threshold', _this._highlightsThreshold);
  65310. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65311. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65312. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65313. };
  65314. };
  65315. // colors shifting and distortion
  65316. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65317. var _this = this;
  65318. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65319. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65320. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65321. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65322. this._depthOfFieldPostProcess.onApply = function (effect) {
  65323. effect.setTexture("depthSampler", _this._depthTexture);
  65324. effect.setTexture("grainSampler", _this._grainTexture);
  65325. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65326. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65327. effect.setFloat('grain_amount', _this._grainAmount);
  65328. effect.setBool('blur_noise', _this._blurNoise);
  65329. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65330. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65331. effect.setFloat('distortion', _this._distortion);
  65332. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65333. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65334. effect.setFloat('aperture', _this._dofAperture);
  65335. effect.setFloat('darken', _this._dofDarken);
  65336. effect.setFloat('edge_blur', _this._edgeBlur);
  65337. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65338. if (_this._scene.activeCamera) {
  65339. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65340. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65341. }
  65342. };
  65343. };
  65344. // creates a black and white random noise texture, 512x512
  65345. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65346. var size = 512;
  65347. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65348. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65349. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65350. var context = this._grainTexture.getContext();
  65351. var rand = function (min, max) {
  65352. return Math.random() * (max - min) + min;
  65353. };
  65354. var value;
  65355. for (var x = 0; x < size; x++) {
  65356. for (var y = 0; y < size; y++) {
  65357. value = Math.floor(rand(0.42, 0.58) * 255);
  65358. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65359. context.fillRect(x, y, 1, 1);
  65360. }
  65361. }
  65362. this._grainTexture.update(false);
  65363. };
  65364. return LensRenderingPipeline;
  65365. }(BABYLON.PostProcessRenderPipeline));
  65366. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65367. })(BABYLON || (BABYLON = {}));
  65368. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65369. var BABYLON;
  65370. (function (BABYLON) {
  65371. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65372. __extends(StandardRenderingPipeline, _super);
  65373. /**
  65374. * @constructor
  65375. * @param {string} name - The rendering pipeline name
  65376. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65377. * @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)
  65378. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65379. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65380. */
  65381. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65382. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65383. var _this = _super.call(this, scene.getEngine(), name) || this;
  65384. _this.downSampleX4PostProcess = null;
  65385. _this.brightPassPostProcess = null;
  65386. _this.blurHPostProcesses = [];
  65387. _this.blurVPostProcesses = [];
  65388. _this.textureAdderPostProcess = null;
  65389. _this.volumetricLightPostProcess = null;
  65390. _this.volumetricLightSmoothXPostProcess = null;
  65391. _this.volumetricLightSmoothYPostProcess = null;
  65392. _this.volumetricLightMergePostProces = null;
  65393. _this.volumetricLightFinalPostProcess = null;
  65394. _this.luminancePostProcess = null;
  65395. _this.luminanceDownSamplePostProcesses = [];
  65396. _this.hdrPostProcess = null;
  65397. _this.textureAdderFinalPostProcess = null;
  65398. _this.lensFlareFinalPostProcess = null;
  65399. _this.hdrFinalPostProcess = null;
  65400. _this.lensFlarePostProcess = null;
  65401. _this.lensFlareComposePostProcess = null;
  65402. _this.motionBlurPostProcess = null;
  65403. _this.depthOfFieldPostProcess = null;
  65404. // Values
  65405. _this.brightThreshold = 1.0;
  65406. _this.blurWidth = 512.0;
  65407. _this.horizontalBlur = false;
  65408. _this.exposure = 1.0;
  65409. _this.lensTexture = null;
  65410. _this.volumetricLightCoefficient = 0.2;
  65411. _this.volumetricLightPower = 4.0;
  65412. _this.volumetricLightBlurScale = 64.0;
  65413. _this.sourceLight = null;
  65414. _this.hdrMinimumLuminance = 1.0;
  65415. _this.hdrDecreaseRate = 0.5;
  65416. _this.hdrIncreaseRate = 0.5;
  65417. _this.lensColorTexture = null;
  65418. _this.lensFlareStrength = 20.0;
  65419. _this.lensFlareGhostDispersal = 1.4;
  65420. _this.lensFlareHaloWidth = 0.7;
  65421. _this.lensFlareDistortionStrength = 16.0;
  65422. _this.lensStarTexture = null;
  65423. _this.lensFlareDirtTexture = null;
  65424. _this.depthOfFieldDistance = 10.0;
  65425. _this.depthOfFieldBlurWidth = 64.0;
  65426. _this.motionStrength = 1.0;
  65427. // IAnimatable
  65428. _this.animations = [];
  65429. _this._currentDepthOfFieldSource = null;
  65430. _this._hdrCurrentLuminance = 1.0;
  65431. // Getters and setters
  65432. _this._bloomEnabled = true;
  65433. _this._depthOfFieldEnabled = false;
  65434. _this._vlsEnabled = false;
  65435. _this._lensFlareEnabled = false;
  65436. _this._hdrEnabled = false;
  65437. _this._motionBlurEnabled = false;
  65438. _this._motionBlurSamples = 64.0;
  65439. _this._volumetricLightStepsCount = 50.0;
  65440. _this._cameras = cameras || [];
  65441. // Initialize
  65442. _this._scene = scene;
  65443. _this._basePostProcess = originalPostProcess;
  65444. _this._ratio = ratio;
  65445. // Misc
  65446. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65447. // Finish
  65448. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65449. _this._buildPipeline();
  65450. return _this;
  65451. }
  65452. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65453. get: function () {
  65454. return this._bloomEnabled;
  65455. },
  65456. set: function (enabled) {
  65457. if (this._bloomEnabled === enabled) {
  65458. return;
  65459. }
  65460. this._bloomEnabled = enabled;
  65461. this._buildPipeline();
  65462. },
  65463. enumerable: true,
  65464. configurable: true
  65465. });
  65466. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65467. get: function () {
  65468. return this._depthOfFieldEnabled;
  65469. },
  65470. set: function (enabled) {
  65471. if (this._depthOfFieldEnabled === enabled) {
  65472. return;
  65473. }
  65474. this._depthOfFieldEnabled = enabled;
  65475. this._buildPipeline();
  65476. },
  65477. enumerable: true,
  65478. configurable: true
  65479. });
  65480. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65481. get: function () {
  65482. return this._lensFlareEnabled;
  65483. },
  65484. set: function (enabled) {
  65485. if (this._lensFlareEnabled === enabled) {
  65486. return;
  65487. }
  65488. this._lensFlareEnabled = enabled;
  65489. this._buildPipeline();
  65490. },
  65491. enumerable: true,
  65492. configurable: true
  65493. });
  65494. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65495. get: function () {
  65496. return this._hdrEnabled;
  65497. },
  65498. set: function (enabled) {
  65499. if (this._hdrEnabled === enabled) {
  65500. return;
  65501. }
  65502. this._hdrEnabled = enabled;
  65503. this._buildPipeline();
  65504. },
  65505. enumerable: true,
  65506. configurable: true
  65507. });
  65508. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65509. get: function () {
  65510. return this._vlsEnabled;
  65511. },
  65512. set: function (enabled) {
  65513. if (this._vlsEnabled === enabled) {
  65514. return;
  65515. }
  65516. if (enabled) {
  65517. var geometry = this._scene.enableGeometryBufferRenderer();
  65518. if (!geometry) {
  65519. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65520. return;
  65521. }
  65522. }
  65523. this._vlsEnabled = enabled;
  65524. this._buildPipeline();
  65525. },
  65526. enumerable: true,
  65527. configurable: true
  65528. });
  65529. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65530. get: function () {
  65531. return this._motionBlurEnabled;
  65532. },
  65533. set: function (enabled) {
  65534. if (this._motionBlurEnabled === enabled) {
  65535. return;
  65536. }
  65537. this._motionBlurEnabled = enabled;
  65538. this._buildPipeline();
  65539. },
  65540. enumerable: true,
  65541. configurable: true
  65542. });
  65543. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65544. get: function () {
  65545. return this._volumetricLightStepsCount;
  65546. },
  65547. set: function (count) {
  65548. if (this.volumetricLightPostProcess) {
  65549. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65550. }
  65551. this._volumetricLightStepsCount = count;
  65552. },
  65553. enumerable: true,
  65554. configurable: true
  65555. });
  65556. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65557. get: function () {
  65558. return this._motionBlurSamples;
  65559. },
  65560. set: function (samples) {
  65561. if (this.motionBlurPostProcess) {
  65562. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65563. }
  65564. this._motionBlurSamples = samples;
  65565. },
  65566. enumerable: true,
  65567. configurable: true
  65568. });
  65569. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65570. var _this = this;
  65571. var ratio = this._ratio;
  65572. var scene = this._scene;
  65573. this._disposePostProcesses();
  65574. this._reset();
  65575. // Create pass post-process
  65576. if (!this._basePostProcess) {
  65577. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65578. this.originalPostProcess.onApply = function (effect) {
  65579. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65580. };
  65581. }
  65582. else {
  65583. this.originalPostProcess = this._basePostProcess;
  65584. }
  65585. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65586. this._currentDepthOfFieldSource = this.originalPostProcess;
  65587. if (this._vlsEnabled) {
  65588. // Create volumetric light
  65589. this._createVolumetricLightPostProcess(scene, ratio);
  65590. // Create volumetric light final post-process
  65591. 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);
  65592. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65593. }
  65594. if (this._bloomEnabled) {
  65595. // Create down sample X4 post-process
  65596. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65597. // Create bright pass post-process
  65598. this._createBrightPassPostProcess(scene, ratio / 2);
  65599. // Create gaussian blur post-processes (down sampling blurs)
  65600. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65601. // Create texture adder post-process
  65602. this._createTextureAdderPostProcess(scene, ratio);
  65603. // Create depth-of-field source post-process
  65604. 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);
  65605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65606. }
  65607. if (this._lensFlareEnabled) {
  65608. // Create lens flare post-process
  65609. this._createLensFlarePostProcess(scene, ratio);
  65610. // Create depth-of-field source post-process post lens-flare and disable it now
  65611. 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);
  65612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65613. }
  65614. if (this._hdrEnabled) {
  65615. // Create luminance
  65616. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65617. // Create HDR
  65618. this._createHdrPostProcess(scene, ratio);
  65619. // Create depth-of-field source post-process post hdr and disable it now
  65620. 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);
  65621. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65622. }
  65623. if (this._depthOfFieldEnabled) {
  65624. // Create gaussian blur used by depth-of-field
  65625. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65626. // Create depth-of-field post-process
  65627. this._createDepthOfFieldPostProcess(scene, ratio);
  65628. }
  65629. if (this._motionBlurEnabled) {
  65630. // Create motion blur post-process
  65631. this._createMotionBlurPostProcess(scene, ratio);
  65632. }
  65633. if (this._cameras !== null) {
  65634. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65635. }
  65636. };
  65637. // Down Sample X4 Post-Processs
  65638. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65639. var _this = this;
  65640. var downSampleX4Offsets = new Array(32);
  65641. 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);
  65642. this.downSampleX4PostProcess.onApply = function (effect) {
  65643. var id = 0;
  65644. var width = _this.downSampleX4PostProcess.width;
  65645. var height = _this.downSampleX4PostProcess.height;
  65646. for (var i = -2; i < 2; i++) {
  65647. for (var j = -2; j < 2; j++) {
  65648. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65649. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65650. id += 2;
  65651. }
  65652. }
  65653. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65654. };
  65655. // Add to pipeline
  65656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65657. };
  65658. // Brightpass Post-Process
  65659. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65660. var _this = this;
  65661. var brightOffsets = new Array(8);
  65662. 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);
  65663. this.brightPassPostProcess.onApply = function (effect) {
  65664. var sU = (1.0 / _this.brightPassPostProcess.width);
  65665. var sV = (1.0 / _this.brightPassPostProcess.height);
  65666. brightOffsets[0] = -0.5 * sU;
  65667. brightOffsets[1] = 0.5 * sV;
  65668. brightOffsets[2] = 0.5 * sU;
  65669. brightOffsets[3] = 0.5 * sV;
  65670. brightOffsets[4] = -0.5 * sU;
  65671. brightOffsets[5] = -0.5 * sV;
  65672. brightOffsets[6] = 0.5 * sU;
  65673. brightOffsets[7] = -0.5 * sV;
  65674. effect.setArray2("dsOffsets", brightOffsets);
  65675. effect.setFloat("brightThreshold", _this.brightThreshold);
  65676. };
  65677. // Add to pipeline
  65678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65679. };
  65680. // Create blur H&V post-processes
  65681. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65682. var _this = this;
  65683. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65684. var engine = scene.getEngine();
  65685. 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);
  65686. 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);
  65687. blurX.onActivateObservable.add(function () {
  65688. var dw = blurX.width / engine.getRenderWidth();
  65689. blurX.kernel = _this[blurWidthKey] * dw;
  65690. });
  65691. blurY.onActivateObservable.add(function () {
  65692. var dw = blurY.height / engine.getRenderHeight();
  65693. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65694. });
  65695. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65697. this.blurHPostProcesses.push(blurX);
  65698. this.blurVPostProcesses.push(blurY);
  65699. };
  65700. // Create texture adder post-process
  65701. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65702. var _this = this;
  65703. 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);
  65704. this.textureAdderPostProcess.onApply = function (effect) {
  65705. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65706. effect.setTexture("lensSampler", _this.lensTexture);
  65707. effect.setFloat("exposure", _this.exposure);
  65708. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65709. };
  65710. // Add to pipeline
  65711. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65712. };
  65713. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65714. var _this = this;
  65715. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65716. geometryRenderer.enablePosition = true;
  65717. var geometry = geometryRenderer.getGBuffer();
  65718. // Base post-process
  65719. 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));
  65720. var depthValues = BABYLON.Vector2.Zero();
  65721. this.volumetricLightPostProcess.onApply = function (effect) {
  65722. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65723. var generator = _this.sourceLight.getShadowGenerator();
  65724. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65725. effect.setTexture("positionSampler", geometry.textures[2]);
  65726. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65727. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65728. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65729. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65730. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65731. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65732. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65733. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65734. effect.setVector2("depthValues", depthValues);
  65735. }
  65736. };
  65737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65738. // Smooth
  65739. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65740. // Merge
  65741. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65742. this.volumetricLightMergePostProces.onApply = function (effect) {
  65743. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65744. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65745. };
  65746. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65747. };
  65748. // Create luminance
  65749. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65750. var _this = this;
  65751. // Create luminance
  65752. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65753. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65754. var offsets = [];
  65755. this.luminancePostProcess.onApply = function (effect) {
  65756. var sU = (1.0 / _this.luminancePostProcess.width);
  65757. var sV = (1.0 / _this.luminancePostProcess.height);
  65758. offsets[0] = -0.5 * sU;
  65759. offsets[1] = 0.5 * sV;
  65760. offsets[2] = 0.5 * sU;
  65761. offsets[3] = 0.5 * sV;
  65762. offsets[4] = -0.5 * sU;
  65763. offsets[5] = -0.5 * sV;
  65764. offsets[6] = 0.5 * sU;
  65765. offsets[7] = -0.5 * sV;
  65766. effect.setArray2("lumOffsets", offsets);
  65767. };
  65768. // Add to pipeline
  65769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65770. // Create down sample luminance
  65771. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65772. var size = Math.pow(3, i);
  65773. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65774. if (i === 0) {
  65775. defines += "#define FINAL_DOWN_SAMPLER";
  65776. }
  65777. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65778. this.luminanceDownSamplePostProcesses.push(postProcess);
  65779. }
  65780. // Create callbacks and add effects
  65781. var lastLuminance = this.luminancePostProcess;
  65782. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65783. var downSampleOffsets = new Array(18);
  65784. pp.onApply = function (effect) {
  65785. if (!lastLuminance) {
  65786. return;
  65787. }
  65788. var id = 0;
  65789. for (var x = -1; x < 2; x++) {
  65790. for (var y = -1; y < 2; y++) {
  65791. downSampleOffsets[id] = x / lastLuminance.width;
  65792. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65793. id += 2;
  65794. }
  65795. }
  65796. effect.setArray2("dsOffsets", downSampleOffsets);
  65797. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65798. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65799. lastLuminance = _this.luminancePostProcess;
  65800. }
  65801. else {
  65802. lastLuminance = pp;
  65803. }
  65804. };
  65805. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65806. pp.onAfterRender = function (effect) {
  65807. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65808. 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);
  65809. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65810. };
  65811. }
  65812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65813. });
  65814. };
  65815. // Create HDR post-process
  65816. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65817. var _this = this;
  65818. 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);
  65819. var outputLiminance = 1;
  65820. var time = 0;
  65821. var lastTime = 0;
  65822. this.hdrPostProcess.onApply = function (effect) {
  65823. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65824. time += scene.getEngine().getDeltaTime();
  65825. if (outputLiminance < 0) {
  65826. outputLiminance = _this._hdrCurrentLuminance;
  65827. }
  65828. else {
  65829. var dt = (lastTime - time) / 1000.0;
  65830. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65831. outputLiminance += _this.hdrDecreaseRate * dt;
  65832. }
  65833. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65834. outputLiminance -= _this.hdrIncreaseRate * dt;
  65835. }
  65836. else {
  65837. outputLiminance = _this._hdrCurrentLuminance;
  65838. }
  65839. }
  65840. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65841. effect.setFloat("averageLuminance", outputLiminance);
  65842. lastTime = time;
  65843. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65844. };
  65845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65846. };
  65847. // Create lens flare post-process
  65848. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65849. var _this = this;
  65850. 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);
  65851. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65852. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65853. 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);
  65854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65855. var resolution = new BABYLON.Vector2(0, 0);
  65856. // Lens flare
  65857. this.lensFlarePostProcess.onApply = function (effect) {
  65858. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65859. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65860. effect.setFloat("strength", _this.lensFlareStrength);
  65861. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65862. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65863. // Shift
  65864. resolution.x = _this.lensFlarePostProcess.width;
  65865. resolution.y = _this.lensFlarePostProcess.height;
  65866. effect.setVector2("resolution", resolution);
  65867. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65868. };
  65869. // Compose
  65870. 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);
  65871. 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);
  65872. this.lensFlareComposePostProcess.onApply = function (effect) {
  65873. if (!_this._scene.activeCamera) {
  65874. return;
  65875. }
  65876. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65877. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  65878. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  65879. // Lens start rotation matrix
  65880. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  65881. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  65882. 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));
  65883. camRot *= 4.0;
  65884. 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);
  65885. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  65886. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  65887. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  65888. };
  65889. };
  65890. // Create depth-of-field post-process
  65891. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  65892. var _this = this;
  65893. 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);
  65894. this.depthOfFieldPostProcess.onApply = function (effect) {
  65895. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65896. effect.setTexture("depthSampler", _this._getDepthTexture());
  65897. effect.setFloat("distance", _this.depthOfFieldDistance);
  65898. };
  65899. // Add to pipeline
  65900. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  65901. };
  65902. // Create motion blur post-process
  65903. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  65904. var _this = this;
  65905. 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);
  65906. var motionScale = 0;
  65907. var prevViewProjection = BABYLON.Matrix.Identity();
  65908. var invViewProjection = BABYLON.Matrix.Identity();
  65909. var viewProjection = BABYLON.Matrix.Identity();
  65910. var screenSize = BABYLON.Vector2.Zero();
  65911. this.motionBlurPostProcess.onApply = function (effect) {
  65912. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  65913. viewProjection.invertToRef(invViewProjection);
  65914. effect.setMatrix("inverseViewProjection", invViewProjection);
  65915. effect.setMatrix("prevViewProjection", prevViewProjection);
  65916. prevViewProjection = viewProjection;
  65917. screenSize.x = _this.motionBlurPostProcess.width;
  65918. screenSize.y = _this.motionBlurPostProcess.height;
  65919. effect.setVector2("screenSize", screenSize);
  65920. motionScale = scene.getEngine().getFps() / 60.0;
  65921. effect.setFloat("motionScale", motionScale);
  65922. effect.setFloat("motionStrength", _this.motionStrength);
  65923. effect.setTexture("depthSampler", _this._getDepthTexture());
  65924. };
  65925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  65926. };
  65927. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  65928. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  65929. var renderer = this._scene.enableGeometryBufferRenderer();
  65930. return renderer.getGBuffer().textures[0];
  65931. }
  65932. return this._scene.enableDepthRenderer().getDepthMap();
  65933. };
  65934. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  65935. for (var i = 0; i < this._cameras.length; i++) {
  65936. var camera = this._cameras[i];
  65937. if (this.originalPostProcess) {
  65938. this.originalPostProcess.dispose(camera);
  65939. }
  65940. if (this.downSampleX4PostProcess) {
  65941. this.downSampleX4PostProcess.dispose(camera);
  65942. }
  65943. if (this.brightPassPostProcess) {
  65944. this.brightPassPostProcess.dispose(camera);
  65945. }
  65946. if (this.textureAdderPostProcess) {
  65947. this.textureAdderPostProcess.dispose(camera);
  65948. }
  65949. if (this.textureAdderFinalPostProcess) {
  65950. this.textureAdderFinalPostProcess.dispose(camera);
  65951. }
  65952. if (this.volumetricLightPostProcess) {
  65953. this.volumetricLightPostProcess.dispose(camera);
  65954. }
  65955. if (this.volumetricLightSmoothXPostProcess) {
  65956. this.volumetricLightSmoothXPostProcess.dispose(camera);
  65957. }
  65958. if (this.volumetricLightSmoothYPostProcess) {
  65959. this.volumetricLightSmoothYPostProcess.dispose(camera);
  65960. }
  65961. if (this.volumetricLightMergePostProces) {
  65962. this.volumetricLightMergePostProces.dispose(camera);
  65963. }
  65964. if (this.volumetricLightFinalPostProcess) {
  65965. this.volumetricLightFinalPostProcess.dispose(camera);
  65966. }
  65967. if (this.lensFlarePostProcess) {
  65968. this.lensFlarePostProcess.dispose(camera);
  65969. }
  65970. if (this.lensFlareComposePostProcess) {
  65971. this.lensFlareComposePostProcess.dispose(camera);
  65972. }
  65973. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  65974. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  65975. }
  65976. if (this.luminancePostProcess) {
  65977. this.luminancePostProcess.dispose(camera);
  65978. }
  65979. if (this.hdrPostProcess) {
  65980. this.hdrPostProcess.dispose(camera);
  65981. }
  65982. if (this.hdrFinalPostProcess) {
  65983. this.hdrFinalPostProcess.dispose(camera);
  65984. }
  65985. if (this.depthOfFieldPostProcess) {
  65986. this.depthOfFieldPostProcess.dispose(camera);
  65987. }
  65988. if (this.motionBlurPostProcess) {
  65989. this.motionBlurPostProcess.dispose(camera);
  65990. }
  65991. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  65992. this.blurHPostProcesses[j].dispose(camera);
  65993. }
  65994. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  65995. this.blurVPostProcesses[j].dispose(camera);
  65996. }
  65997. }
  65998. this.originalPostProcess = null;
  65999. this.downSampleX4PostProcess = null;
  66000. this.brightPassPostProcess = null;
  66001. this.textureAdderPostProcess = null;
  66002. this.textureAdderFinalPostProcess = null;
  66003. this.volumetricLightPostProcess = null;
  66004. this.volumetricLightSmoothXPostProcess = null;
  66005. this.volumetricLightSmoothYPostProcess = null;
  66006. this.volumetricLightMergePostProces = null;
  66007. this.volumetricLightFinalPostProcess = null;
  66008. this.lensFlarePostProcess = null;
  66009. this.lensFlareComposePostProcess = null;
  66010. this.luminancePostProcess = null;
  66011. this.hdrPostProcess = null;
  66012. this.hdrFinalPostProcess = null;
  66013. this.depthOfFieldPostProcess = null;
  66014. this.motionBlurPostProcess = null;
  66015. this.luminanceDownSamplePostProcesses = [];
  66016. this.blurHPostProcesses = [];
  66017. this.blurVPostProcesses = [];
  66018. };
  66019. // Dispose
  66020. StandardRenderingPipeline.prototype.dispose = function () {
  66021. this._disposePostProcesses();
  66022. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66023. _super.prototype.dispose.call(this);
  66024. };
  66025. // Serialize rendering pipeline
  66026. StandardRenderingPipeline.prototype.serialize = function () {
  66027. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66028. serializationObject.customType = "StandardRenderingPipeline";
  66029. return serializationObject;
  66030. };
  66031. /**
  66032. * Static members
  66033. */
  66034. // Parse serialized pipeline
  66035. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66036. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66037. };
  66038. // Luminance steps
  66039. StandardRenderingPipeline.LuminanceSteps = 6;
  66040. __decorate([
  66041. BABYLON.serialize()
  66042. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66043. __decorate([
  66044. BABYLON.serialize()
  66045. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66046. __decorate([
  66047. BABYLON.serialize()
  66048. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66049. __decorate([
  66050. BABYLON.serialize()
  66051. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66052. __decorate([
  66053. BABYLON.serializeAsTexture("lensTexture")
  66054. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66055. __decorate([
  66056. BABYLON.serialize()
  66057. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66058. __decorate([
  66059. BABYLON.serialize()
  66060. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66061. __decorate([
  66062. BABYLON.serialize()
  66063. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66064. __decorate([
  66065. BABYLON.serialize()
  66066. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66067. __decorate([
  66068. BABYLON.serialize()
  66069. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66070. __decorate([
  66071. BABYLON.serialize()
  66072. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66073. __decorate([
  66074. BABYLON.serializeAsTexture("lensColorTexture")
  66075. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66076. __decorate([
  66077. BABYLON.serialize()
  66078. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66079. __decorate([
  66080. BABYLON.serialize()
  66081. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66082. __decorate([
  66083. BABYLON.serialize()
  66084. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66085. __decorate([
  66086. BABYLON.serialize()
  66087. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66088. __decorate([
  66089. BABYLON.serializeAsTexture("lensStarTexture")
  66090. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66091. __decorate([
  66092. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66093. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66094. __decorate([
  66095. BABYLON.serialize()
  66096. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66097. __decorate([
  66098. BABYLON.serialize()
  66099. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66100. __decorate([
  66101. BABYLON.serialize()
  66102. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66103. __decorate([
  66104. BABYLON.serialize()
  66105. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66106. __decorate([
  66107. BABYLON.serialize()
  66108. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66109. __decorate([
  66110. BABYLON.serialize()
  66111. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66112. __decorate([
  66113. BABYLON.serialize()
  66114. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66115. __decorate([
  66116. BABYLON.serialize()
  66117. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66118. __decorate([
  66119. BABYLON.serialize()
  66120. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66121. __decorate([
  66122. BABYLON.serialize()
  66123. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66124. __decorate([
  66125. BABYLON.serialize()
  66126. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66127. __decorate([
  66128. BABYLON.serialize()
  66129. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66130. return StandardRenderingPipeline;
  66131. }(BABYLON.PostProcessRenderPipeline));
  66132. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66133. })(BABYLON || (BABYLON = {}));
  66134. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66135. var BABYLON;
  66136. (function (BABYLON) {
  66137. var FxaaPostProcess = /** @class */ (function (_super) {
  66138. __extends(FxaaPostProcess, _super);
  66139. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66140. if (camera === void 0) { camera = null; }
  66141. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66142. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66143. _this.onApplyObservable.add(function (effect) {
  66144. var texelSize = _this.texelSize;
  66145. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66146. });
  66147. return _this;
  66148. }
  66149. return FxaaPostProcess;
  66150. }(BABYLON.PostProcess));
  66151. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66152. })(BABYLON || (BABYLON = {}));
  66153. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66154. var BABYLON;
  66155. (function (BABYLON) {
  66156. /**
  66157. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66158. */
  66159. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66160. __extends(CircleOfConfusionPostProcess, _super);
  66161. /**
  66162. * Creates a new instance of @see CircleOfConfusionPostProcess
  66163. * @param name The name of the effect.
  66164. * @param scene The scene the effect belongs to.
  66165. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66166. * @param options The required width/height ratio to downsize to before computing the render pass.
  66167. * @param camera The camera to apply the render pass to.
  66168. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66169. * @param engine The engine which the post process will be applied. (default: current engine)
  66170. * @param reusable If the post process can be reused on the same frame. (default: false)
  66171. * @param textureType Type of textures used when performing the post process. (default: 0)
  66172. */
  66173. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66174. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66175. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66176. /**
  66177. * 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.
  66178. */
  66179. _this.lensSize = 50;
  66180. /**
  66181. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66182. */
  66183. _this.fStop = 1.4;
  66184. /**
  66185. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66186. */
  66187. _this.focusDistance = 2000;
  66188. /**
  66189. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66190. */
  66191. _this.focalLength = 50;
  66192. _this.onApplyObservable.add(function (effect) {
  66193. effect.setTexture("depthSampler", depthTexture);
  66194. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66195. var aperture = _this.lensSize / _this.fStop;
  66196. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66197. effect.setFloat('focusDistance', _this.focusDistance);
  66198. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66199. if (scene.activeCamera) {
  66200. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66201. }
  66202. });
  66203. return _this;
  66204. }
  66205. return CircleOfConfusionPostProcess;
  66206. }(BABYLON.PostProcess));
  66207. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66208. })(BABYLON || (BABYLON = {}));
  66209. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66210. var BABYLON;
  66211. (function (BABYLON) {
  66212. /**
  66213. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66214. */
  66215. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66216. __extends(DepthOfFieldMergePostProcess, _super);
  66217. /**
  66218. * Creates a new instance of @see CircleOfConfusionPostProcess
  66219. * @param name The name of the effect.
  66220. * @param original The non-blurred image to be modified
  66221. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66222. * @param blurSteps Incrimental bluring post processes.
  66223. * @param options The required width/height ratio to downsize to before computing the render pass.
  66224. * @param camera The camera to apply the render pass to.
  66225. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66226. * @param engine The engine which the post process will be applied. (default: current engine)
  66227. * @param reusable If the post process can be reused on the same frame. (default: false)
  66228. * @param textureType Type of textures used when performing the post process. (default: 0)
  66229. */
  66230. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66231. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66232. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66233. _this.onApplyObservable.add(function (effect) {
  66234. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66235. effect.setTextureFromPostProcess("originalSampler", original);
  66236. blurSteps.forEach(function (step, index) {
  66237. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66238. });
  66239. });
  66240. return _this;
  66241. }
  66242. return DepthOfFieldMergePostProcess;
  66243. }(BABYLON.PostProcess));
  66244. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66245. })(BABYLON || (BABYLON = {}));
  66246. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66247. var BABYLON;
  66248. (function (BABYLON) {
  66249. /**
  66250. * Specifies the level of max blur that should be applied when using the depth of field effect
  66251. */
  66252. var DepthOfFieldEffectBlurLevel;
  66253. (function (DepthOfFieldEffectBlurLevel) {
  66254. /**
  66255. * Subtle blur
  66256. */
  66257. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66258. /**
  66259. * Medium blur
  66260. */
  66261. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66262. /**
  66263. * Large blur
  66264. */
  66265. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66266. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66267. ;
  66268. /**
  66269. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66270. */
  66271. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66272. __extends(DepthOfFieldEffect, _super);
  66273. /**
  66274. * Creates a new instance of @see DepthOfFieldEffect
  66275. * @param scene The scene the effect belongs to.
  66276. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66277. */
  66278. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66279. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66280. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66281. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66282. // Enable and get current depth map
  66283. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66284. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66285. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66286. // Capture circle of confusion texture
  66287. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66288. _this._depthOfFieldPass.autoClear = false;
  66289. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  66290. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66291. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66292. _this._depthOfFieldBlurY = [];
  66293. _this._depthOfFieldBlurX = [];
  66294. var blurCount = 1;
  66295. var kernelSize = 15;
  66296. switch (blurLevel) {
  66297. case DepthOfFieldEffectBlurLevel.High: {
  66298. blurCount = 3;
  66299. kernelSize = 51;
  66300. break;
  66301. }
  66302. case DepthOfFieldEffectBlurLevel.Medium: {
  66303. blurCount = 2;
  66304. kernelSize = 31;
  66305. break;
  66306. }
  66307. default: {
  66308. kernelSize = 15;
  66309. blurCount = 1;
  66310. break;
  66311. }
  66312. }
  66313. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66314. for (var i = 0; i < blurCount; i++) {
  66315. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66316. blurY.autoClear = false;
  66317. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66318. blurX.autoClear = false;
  66319. _this._depthOfFieldBlurY.push(blurY);
  66320. _this._depthOfFieldBlurX.push(blurX);
  66321. }
  66322. // Merge blurred images with original image based on circleOfConfusion
  66323. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66324. _this._depthOfFieldMerge.autoClear = false;
  66325. // Set all post processes on the effect.
  66326. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66327. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66328. effects.push(_this._depthOfFieldBlurY[i]);
  66329. effects.push(_this._depthOfFieldBlurX[i]);
  66330. }
  66331. effects.push(_this._depthOfFieldMerge);
  66332. return effects;
  66333. }, true) || this;
  66334. return _this;
  66335. }
  66336. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66337. get: function () {
  66338. return this._circleOfConfusion.focalLength;
  66339. },
  66340. /**
  66341. * The focal the length of the camera used in the effect
  66342. */
  66343. set: function (value) {
  66344. this._circleOfConfusion.focalLength = value;
  66345. },
  66346. enumerable: true,
  66347. configurable: true
  66348. });
  66349. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66350. get: function () {
  66351. return this._circleOfConfusion.fStop;
  66352. },
  66353. /**
  66354. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66355. */
  66356. set: function (value) {
  66357. this._circleOfConfusion.fStop = value;
  66358. },
  66359. enumerable: true,
  66360. configurable: true
  66361. });
  66362. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66363. get: function () {
  66364. return this._circleOfConfusion.focusDistance;
  66365. },
  66366. /**
  66367. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66368. */
  66369. set: function (value) {
  66370. this._circleOfConfusion.focusDistance = value;
  66371. },
  66372. enumerable: true,
  66373. configurable: true
  66374. });
  66375. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66376. get: function () {
  66377. return this._circleOfConfusion.lensSize;
  66378. },
  66379. /**
  66380. * 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.
  66381. */
  66382. set: function (value) {
  66383. this._circleOfConfusion.lensSize = value;
  66384. },
  66385. enumerable: true,
  66386. configurable: true
  66387. });
  66388. /**
  66389. * Disposes each of the internal effects for a given camera.
  66390. * @param camera The camera to dispose the effect on.
  66391. */
  66392. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66393. this._depthOfFieldPass.dispose(camera);
  66394. this._circleOfConfusion.dispose(camera);
  66395. this._depthOfFieldBlurX.forEach(function (element) {
  66396. element.dispose(camera);
  66397. });
  66398. this._depthOfFieldBlurY.forEach(function (element) {
  66399. element.dispose(camera);
  66400. });
  66401. this._depthOfFieldMerge.dispose(camera);
  66402. };
  66403. return DepthOfFieldEffect;
  66404. }(BABYLON.PostProcessRenderEffect));
  66405. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66406. })(BABYLON || (BABYLON = {}));
  66407. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66408. var BABYLON;
  66409. (function (BABYLON) {
  66410. /**
  66411. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66412. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66413. */
  66414. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66415. __extends(DefaultRenderingPipeline, _super);
  66416. /**
  66417. * @constructor
  66418. * @param {string} name - The rendering pipeline name
  66419. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66420. * @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)
  66421. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66422. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66423. */
  66424. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66425. if (automaticBuild === void 0) { automaticBuild = true; }
  66426. var _this = _super.call(this, scene.getEngine(), name) || this;
  66427. /**
  66428. * ID of the pass post process used for bloom,
  66429. */
  66430. _this.PassPostProcessId = "PassPostProcessEffect";
  66431. /**
  66432. * ID of the highlight post process used for bloom,
  66433. */
  66434. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66435. /**
  66436. * ID of the blurX post process used for bloom,
  66437. */
  66438. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66439. /**
  66440. * ID of the blurY post process used for bloom,
  66441. */
  66442. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66443. /**
  66444. * ID of the copy back post process used for bloom,
  66445. */
  66446. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66447. /**
  66448. * ID of the image processing post process;
  66449. */
  66450. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66451. /**
  66452. * ID of the Fast Approximate Anti-Aliasing post process;
  66453. */
  66454. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66455. /**
  66456. * ID of the final merge post process;
  66457. */
  66458. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66459. /**
  66460. * Animations which can be used to tweak settings over a period of time
  66461. */
  66462. _this.animations = [];
  66463. // Values
  66464. _this._bloomEnabled = false;
  66465. _this._depthOfFieldEnabled = false;
  66466. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66467. _this._fxaaEnabled = false;
  66468. _this._imageProcessingEnabled = true;
  66469. _this._bloomScale = 0.6;
  66470. _this._buildAllowed = true;
  66471. /**
  66472. * Specifies the size of the bloom blur kernel, relative to the final output size
  66473. */
  66474. _this.bloomKernel = 64;
  66475. /**
  66476. * Specifies the weight of the bloom in the final rendering
  66477. */
  66478. _this._bloomWeight = 0.15;
  66479. _this._cameras = cameras || [];
  66480. _this._buildAllowed = automaticBuild;
  66481. // Initialize
  66482. _this._scene = scene;
  66483. var caps = _this._scene.getEngine().getCaps();
  66484. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66485. // Misc
  66486. if (_this._hdr) {
  66487. if (caps.textureHalfFloatRender) {
  66488. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66489. }
  66490. else if (caps.textureFloatRender) {
  66491. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66492. }
  66493. }
  66494. else {
  66495. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66496. }
  66497. // Attach
  66498. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66499. _this._buildPipeline();
  66500. return _this;
  66501. }
  66502. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66503. get: function () {
  66504. return this._bloomWeight;
  66505. },
  66506. /**
  66507. * The strength of the bloom.
  66508. */
  66509. set: function (value) {
  66510. if (this._bloomWeight === value) {
  66511. return;
  66512. }
  66513. this._bloomWeight = value;
  66514. if (this._hdr && this.copyBack) {
  66515. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66516. }
  66517. },
  66518. enumerable: true,
  66519. configurable: true
  66520. });
  66521. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66522. get: function () {
  66523. return this._bloomScale;
  66524. },
  66525. /**
  66526. * The scale of the bloom, lower value will provide better performance.
  66527. */
  66528. set: function (value) {
  66529. if (this._bloomScale === value) {
  66530. return;
  66531. }
  66532. this._bloomScale = value;
  66533. this._buildPipeline();
  66534. },
  66535. enumerable: true,
  66536. configurable: true
  66537. });
  66538. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66539. get: function () {
  66540. return this._bloomEnabled;
  66541. },
  66542. /**
  66543. * Enable or disable the bloom from the pipeline
  66544. */
  66545. set: function (enabled) {
  66546. if (this._bloomEnabled === enabled) {
  66547. return;
  66548. }
  66549. this._bloomEnabled = enabled;
  66550. this._buildPipeline();
  66551. },
  66552. enumerable: true,
  66553. configurable: true
  66554. });
  66555. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66556. /**
  66557. * If the depth of field is enabled.
  66558. */
  66559. get: function () {
  66560. return this._depthOfFieldEnabled;
  66561. },
  66562. set: function (enabled) {
  66563. if (this._depthOfFieldEnabled === enabled) {
  66564. return;
  66565. }
  66566. this._depthOfFieldEnabled = enabled;
  66567. this._buildPipeline();
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66573. /**
  66574. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66575. */
  66576. get: function () {
  66577. return this._depthOfFieldBlurLevel;
  66578. },
  66579. set: function (value) {
  66580. if (this._depthOfFieldBlurLevel === value) {
  66581. return;
  66582. }
  66583. this._depthOfFieldBlurLevel = value;
  66584. this._buildPipeline();
  66585. },
  66586. enumerable: true,
  66587. configurable: true
  66588. });
  66589. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66590. get: function () {
  66591. return this._fxaaEnabled;
  66592. },
  66593. /**
  66594. * If the anti aliasing is enabled.
  66595. */
  66596. set: function (enabled) {
  66597. if (this._fxaaEnabled === enabled) {
  66598. return;
  66599. }
  66600. this._fxaaEnabled = enabled;
  66601. this._buildPipeline();
  66602. },
  66603. enumerable: true,
  66604. configurable: true
  66605. });
  66606. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66607. get: function () {
  66608. return this._imageProcessingEnabled;
  66609. },
  66610. /**
  66611. * If image processing is enabled.
  66612. */
  66613. set: function (enabled) {
  66614. if (this._imageProcessingEnabled === enabled) {
  66615. return;
  66616. }
  66617. this._imageProcessingEnabled = enabled;
  66618. this._buildPipeline();
  66619. },
  66620. enumerable: true,
  66621. configurable: true
  66622. });
  66623. /**
  66624. * Force the compilation of the entire pipeline.
  66625. */
  66626. DefaultRenderingPipeline.prototype.prepare = function () {
  66627. var previousState = this._buildAllowed;
  66628. this._buildAllowed = true;
  66629. this._buildPipeline();
  66630. this._buildAllowed = previousState;
  66631. };
  66632. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66633. var _this = this;
  66634. if (!this._buildAllowed) {
  66635. return;
  66636. }
  66637. var engine = this._scene.getEngine();
  66638. this._disposePostProcesses();
  66639. this._reset();
  66640. if (this.depthOfFieldEnabled) {
  66641. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66642. this.addEffect(this.depthOfField);
  66643. }
  66644. if (this.bloomEnabled) {
  66645. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66646. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66647. if (!this._hdr) {
  66648. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66649. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66650. this.highlights.autoClear = false;
  66651. this.highlights.alwaysForcePOT = true;
  66652. }
  66653. 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);
  66654. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66655. this.blurX.alwaysForcePOT = true;
  66656. this.blurX.autoClear = false;
  66657. this.blurX.onActivateObservable.add(function () {
  66658. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66659. _this.blurX.kernel = _this.bloomKernel * dw;
  66660. });
  66661. 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);
  66662. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66663. this.blurY.alwaysForcePOT = true;
  66664. this.blurY.autoClear = false;
  66665. this.blurY.onActivateObservable.add(function () {
  66666. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66667. _this.blurY.kernel = _this.bloomKernel * dh;
  66668. });
  66669. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66670. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66671. this.copyBack.alwaysForcePOT = true;
  66672. if (this._hdr) {
  66673. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66674. var w = this.bloomWeight;
  66675. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66676. }
  66677. else {
  66678. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66679. }
  66680. this.copyBack.autoClear = false;
  66681. }
  66682. if (this._imageProcessingEnabled) {
  66683. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66684. if (this._hdr) {
  66685. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66686. }
  66687. else {
  66688. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66689. }
  66690. }
  66691. if (this.fxaaEnabled) {
  66692. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66693. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66694. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66695. }
  66696. else if (this._hdr && this.imageProcessing) {
  66697. this.finalMerge = this.imageProcessing;
  66698. }
  66699. else {
  66700. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66701. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66702. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66703. }
  66704. if (this.bloomEnabled) {
  66705. if (this._hdr) {
  66706. this.copyBack.shareOutputWith(this.blurX);
  66707. if (this.imageProcessing) {
  66708. this.imageProcessing.shareOutputWith(this.pass);
  66709. this.imageProcessing.autoClear = false;
  66710. }
  66711. else if (this.fxaa) {
  66712. this.fxaa.shareOutputWith(this.pass);
  66713. }
  66714. else {
  66715. this.finalMerge.shareOutputWith(this.pass);
  66716. }
  66717. }
  66718. else {
  66719. if (this.fxaa) {
  66720. this.fxaa.shareOutputWith(this.pass);
  66721. }
  66722. else {
  66723. this.finalMerge.shareOutputWith(this.pass);
  66724. }
  66725. }
  66726. }
  66727. if (this._cameras !== null) {
  66728. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66729. }
  66730. };
  66731. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66732. for (var i = 0; i < this._cameras.length; i++) {
  66733. var camera = this._cameras[i];
  66734. if (this.pass) {
  66735. this.pass.dispose(camera);
  66736. }
  66737. if (this.highlights) {
  66738. this.highlights.dispose(camera);
  66739. }
  66740. if (this.blurX) {
  66741. this.blurX.dispose(camera);
  66742. }
  66743. if (this.blurY) {
  66744. this.blurY.dispose(camera);
  66745. }
  66746. if (this.copyBack) {
  66747. this.copyBack.dispose(camera);
  66748. }
  66749. if (this.imageProcessing) {
  66750. this.imageProcessing.dispose(camera);
  66751. }
  66752. if (this.fxaa) {
  66753. this.fxaa.dispose(camera);
  66754. }
  66755. if (this.finalMerge) {
  66756. this.finalMerge.dispose(camera);
  66757. }
  66758. if (this.depthOfField) {
  66759. this.depthOfField.disposeEffects(camera);
  66760. }
  66761. }
  66762. this.pass = null;
  66763. this.highlights = null;
  66764. this.blurX = null;
  66765. this.blurY = null;
  66766. this.copyBack = null;
  66767. this.imageProcessing = null;
  66768. this.fxaa = null;
  66769. this.finalMerge = null;
  66770. this.depthOfField = null;
  66771. };
  66772. /**
  66773. * Dispose of the pipeline and stop all post processes
  66774. */
  66775. DefaultRenderingPipeline.prototype.dispose = function () {
  66776. this._disposePostProcesses();
  66777. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66778. _super.prototype.dispose.call(this);
  66779. };
  66780. /**
  66781. * Serialize the rendering pipeline (Used when exporting)
  66782. * @returns the serialized object
  66783. */
  66784. DefaultRenderingPipeline.prototype.serialize = function () {
  66785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66786. serializationObject.customType = "DefaultRenderingPipeline";
  66787. return serializationObject;
  66788. };
  66789. /**
  66790. * Parse the serialized pipeline
  66791. * @param source Source pipeline.
  66792. * @param scene The scene to load the pipeline to.
  66793. * @param rootUrl The URL of the serialized pipeline.
  66794. * @returns An instantiated pipeline from the serialized object.
  66795. */
  66796. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66797. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66798. };
  66799. __decorate([
  66800. BABYLON.serialize()
  66801. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66802. __decorate([
  66803. BABYLON.serialize()
  66804. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66805. __decorate([
  66806. BABYLON.serialize()
  66807. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66808. __decorate([
  66809. BABYLON.serialize()
  66810. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66811. __decorate([
  66812. BABYLON.serialize()
  66813. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66814. __decorate([
  66815. BABYLON.serialize()
  66816. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66817. __decorate([
  66818. BABYLON.serialize()
  66819. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66820. __decorate([
  66821. BABYLON.serialize()
  66822. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  66823. __decorate([
  66824. BABYLON.serialize()
  66825. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66826. __decorate([
  66827. BABYLON.serialize()
  66828. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66829. return DefaultRenderingPipeline;
  66830. }(BABYLON.PostProcessRenderPipeline));
  66831. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66832. })(BABYLON || (BABYLON = {}));
  66833. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66834. var BABYLON;
  66835. (function (BABYLON) {
  66836. /**
  66837. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66838. */
  66839. var GeometryBufferRenderer = /** @class */ (function () {
  66840. /**
  66841. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66842. * @param scene The scene the buffer belongs to
  66843. * @param ratio How big is the buffer related to the main canvas.
  66844. */
  66845. function GeometryBufferRenderer(scene, ratio) {
  66846. if (ratio === void 0) { ratio = 1; }
  66847. this._enablePosition = false;
  66848. this._scene = scene;
  66849. this._ratio = ratio;
  66850. // Render target
  66851. this._createRenderTargets();
  66852. }
  66853. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66854. /**
  66855. * Set the render list (meshes to be rendered) used in the G buffer.
  66856. */
  66857. set: function (meshes) {
  66858. this._multiRenderTarget.renderList = meshes;
  66859. },
  66860. enumerable: true,
  66861. configurable: true
  66862. });
  66863. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66864. /**
  66865. * Gets wether or not G buffer are supported by the running hardware.
  66866. * This requires draw buffer supports
  66867. */
  66868. get: function () {
  66869. return this._multiRenderTarget.isSupported;
  66870. },
  66871. enumerable: true,
  66872. configurable: true
  66873. });
  66874. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66875. /**
  66876. * Gets wether or not position are enabled for the G buffer.
  66877. */
  66878. get: function () {
  66879. return this._enablePosition;
  66880. },
  66881. /**
  66882. * Sets wether or not position are enabled for the G buffer.
  66883. */
  66884. set: function (enable) {
  66885. this._enablePosition = enable;
  66886. this.dispose();
  66887. this._createRenderTargets();
  66888. },
  66889. enumerable: true,
  66890. configurable: true
  66891. });
  66892. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  66893. /**
  66894. * Gets the scene associated with the buffer.
  66895. */
  66896. get: function () {
  66897. return this._scene;
  66898. },
  66899. enumerable: true,
  66900. configurable: true
  66901. });
  66902. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  66903. /**
  66904. * Gets the ratio used by the buffer during its creation.
  66905. * How big is the buffer related to the main canvas.
  66906. */
  66907. get: function () {
  66908. return this._ratio;
  66909. },
  66910. enumerable: true,
  66911. configurable: true
  66912. });
  66913. /**
  66914. * Checks wether everything is ready to render a submesh to the G buffer.
  66915. * @param subMesh the submesh to check readiness for
  66916. * @param useInstances is the mesh drawn using instance or not
  66917. * @returns true if ready otherwise false
  66918. */
  66919. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  66920. var material = subMesh.getMaterial();
  66921. if (material && material.disableDepthWrite) {
  66922. return false;
  66923. }
  66924. var defines = [];
  66925. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66926. var mesh = subMesh.getMesh();
  66927. // Alpha test
  66928. if (material && material.needAlphaTesting()) {
  66929. defines.push("#define ALPHATEST");
  66930. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66931. attribs.push(BABYLON.VertexBuffer.UVKind);
  66932. defines.push("#define UV1");
  66933. }
  66934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66935. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66936. defines.push("#define UV2");
  66937. }
  66938. }
  66939. // Buffers
  66940. if (this._enablePosition) {
  66941. defines.push("#define POSITION");
  66942. }
  66943. // Bones
  66944. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66947. if (mesh.numBoneInfluencers > 4) {
  66948. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66949. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66950. }
  66951. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66952. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66953. }
  66954. else {
  66955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66956. }
  66957. // Instances
  66958. if (useInstances) {
  66959. defines.push("#define INSTANCES");
  66960. attribs.push("world0");
  66961. attribs.push("world1");
  66962. attribs.push("world2");
  66963. attribs.push("world3");
  66964. }
  66965. // Get correct effect
  66966. var join = defines.join("\n");
  66967. if (this._cachedDefines !== join) {
  66968. this._cachedDefines = join;
  66969. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  66970. }
  66971. return this._effect.isReady();
  66972. };
  66973. /**
  66974. * Gets the current underlying G Buffer.
  66975. * @returns the buffer
  66976. */
  66977. GeometryBufferRenderer.prototype.getGBuffer = function () {
  66978. return this._multiRenderTarget;
  66979. };
  66980. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  66981. /**
  66982. * Gets the number of samples used to render the buffer (anti aliasing).
  66983. */
  66984. get: function () {
  66985. return this._multiRenderTarget.samples;
  66986. },
  66987. /**
  66988. * Sets the number of samples used to render the buffer (anti aliasing).
  66989. */
  66990. set: function (value) {
  66991. this._multiRenderTarget.samples = value;
  66992. },
  66993. enumerable: true,
  66994. configurable: true
  66995. });
  66996. /**
  66997. * Disposes the renderer and frees up associated resources.
  66998. */
  66999. GeometryBufferRenderer.prototype.dispose = function () {
  67000. this.getGBuffer().dispose();
  67001. };
  67002. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67003. var _this = this;
  67004. var engine = this._scene.getEngine();
  67005. var count = this._enablePosition ? 3 : 2;
  67006. 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 });
  67007. if (!this.isSupported) {
  67008. return;
  67009. }
  67010. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67011. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67012. this._multiRenderTarget.refreshRate = 1;
  67013. this._multiRenderTarget.renderParticles = false;
  67014. this._multiRenderTarget.renderList = null;
  67015. // set default depth value to 1.0 (far away)
  67016. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67017. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67018. });
  67019. // Custom render function
  67020. var renderSubMesh = function (subMesh) {
  67021. var mesh = subMesh.getRenderingMesh();
  67022. var scene = _this._scene;
  67023. var engine = scene.getEngine();
  67024. var material = subMesh.getMaterial();
  67025. if (!material) {
  67026. return;
  67027. }
  67028. // Culling
  67029. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67030. // Managing instances
  67031. var batch = mesh._getInstancesRenderList(subMesh._id);
  67032. if (batch.mustReturn) {
  67033. return;
  67034. }
  67035. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67036. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67037. engine.enableEffect(_this._effect);
  67038. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67039. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67040. _this._effect.setMatrix("view", scene.getViewMatrix());
  67041. // Alpha test
  67042. if (material && material.needAlphaTesting()) {
  67043. var alphaTexture = material.getAlphaTestTexture();
  67044. if (alphaTexture) {
  67045. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67046. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67047. }
  67048. }
  67049. // Bones
  67050. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67051. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67052. }
  67053. // Draw
  67054. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67055. }
  67056. };
  67057. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67058. var index;
  67059. if (depthOnlySubMeshes.length) {
  67060. engine.setColorWrite(false);
  67061. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67062. renderSubMesh(depthOnlySubMeshes.data[index]);
  67063. }
  67064. engine.setColorWrite(true);
  67065. }
  67066. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67067. renderSubMesh(opaqueSubMeshes.data[index]);
  67068. }
  67069. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67070. renderSubMesh(alphaTestSubMeshes.data[index]);
  67071. }
  67072. };
  67073. };
  67074. return GeometryBufferRenderer;
  67075. }());
  67076. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67077. })(BABYLON || (BABYLON = {}));
  67078. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67079. var BABYLON;
  67080. (function (BABYLON) {
  67081. var RefractionPostProcess = /** @class */ (function (_super) {
  67082. __extends(RefractionPostProcess, _super);
  67083. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67084. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67085. _this.color = color;
  67086. _this.depth = depth;
  67087. _this.colorLevel = colorLevel;
  67088. _this.onActivateObservable.add(function (cam) {
  67089. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67090. });
  67091. _this.onApplyObservable.add(function (effect) {
  67092. effect.setColor3("baseColor", _this.color);
  67093. effect.setFloat("depth", _this.depth);
  67094. effect.setFloat("colorLevel", _this.colorLevel);
  67095. effect.setTexture("refractionSampler", _this._refRexture);
  67096. });
  67097. return _this;
  67098. }
  67099. // Methods
  67100. RefractionPostProcess.prototype.dispose = function (camera) {
  67101. if (this._refRexture) {
  67102. this._refRexture.dispose();
  67103. }
  67104. _super.prototype.dispose.call(this, camera);
  67105. };
  67106. return RefractionPostProcess;
  67107. }(BABYLON.PostProcess));
  67108. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67109. })(BABYLON || (BABYLON = {}));
  67110. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67111. var BABYLON;
  67112. (function (BABYLON) {
  67113. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67114. __extends(BlackAndWhitePostProcess, _super);
  67115. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67116. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67117. _this.degree = 1;
  67118. _this.onApplyObservable.add(function (effect) {
  67119. effect.setFloat("degree", _this.degree);
  67120. });
  67121. return _this;
  67122. }
  67123. return BlackAndWhitePostProcess;
  67124. }(BABYLON.PostProcess));
  67125. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67126. })(BABYLON || (BABYLON = {}));
  67127. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67128. var BABYLON;
  67129. (function (BABYLON) {
  67130. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67131. __extends(ConvolutionPostProcess, _super);
  67132. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67133. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67134. _this.kernel = kernel;
  67135. _this.onApply = function (effect) {
  67136. effect.setFloat2("screenSize", _this.width, _this.height);
  67137. effect.setArray("kernel", _this.kernel);
  67138. };
  67139. return _this;
  67140. }
  67141. // Statics
  67142. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67143. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67144. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67145. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67146. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67147. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67148. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67149. return ConvolutionPostProcess;
  67150. }(BABYLON.PostProcess));
  67151. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67152. })(BABYLON || (BABYLON = {}));
  67153. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67154. var BABYLON;
  67155. (function (BABYLON) {
  67156. var FilterPostProcess = /** @class */ (function (_super) {
  67157. __extends(FilterPostProcess, _super);
  67158. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67159. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67160. _this.kernelMatrix = kernelMatrix;
  67161. _this.onApply = function (effect) {
  67162. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67163. };
  67164. return _this;
  67165. }
  67166. return FilterPostProcess;
  67167. }(BABYLON.PostProcess));
  67168. BABYLON.FilterPostProcess = FilterPostProcess;
  67169. })(BABYLON || (BABYLON = {}));
  67170. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67171. var BABYLON;
  67172. (function (BABYLON) {
  67173. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67174. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67175. __extends(VolumetricLightScatteringPostProcess, _super);
  67176. /**
  67177. * @constructor
  67178. * @param {string} name - The post-process name
  67179. * @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)
  67180. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67181. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67182. * @param {number} samples - The post-process quality, default 100
  67183. * @param {number} samplingMode - The post-process filtering mode
  67184. * @param {BABYLON.Engine} engine - The babylon engine
  67185. * @param {boolean} reusable - If the post-process is reusable
  67186. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67187. */
  67188. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67189. if (samples === void 0) { samples = 100; }
  67190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67191. 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;
  67192. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67193. /**
  67194. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67195. * @type {Vector3}
  67196. */
  67197. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67198. /**
  67199. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67200. * @type {boolean}
  67201. */
  67202. _this.useCustomMeshPosition = false;
  67203. /**
  67204. * If the post-process should inverse the light scattering direction
  67205. * @type {boolean}
  67206. */
  67207. _this.invert = true;
  67208. /**
  67209. * Array containing the excluded meshes not rendered in the internal pass
  67210. */
  67211. _this.excludedMeshes = new Array();
  67212. /**
  67213. * Controls the overall intensity of the post-process
  67214. * @type {number}
  67215. */
  67216. _this.exposure = 0.3;
  67217. /**
  67218. * Dissipates each sample's contribution in range [0, 1]
  67219. * @type {number}
  67220. */
  67221. _this.decay = 0.96815;
  67222. /**
  67223. * Controls the overall intensity of each sample
  67224. * @type {number}
  67225. */
  67226. _this.weight = 0.58767;
  67227. /**
  67228. * Controls the density of each sample
  67229. * @type {number}
  67230. */
  67231. _this.density = 0.926;
  67232. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67233. engine = scene.getEngine();
  67234. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67235. // Configure mesh
  67236. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67237. // Configure
  67238. _this._createPass(scene, ratio.passRatio || ratio);
  67239. _this.onActivate = function (camera) {
  67240. if (!_this.isSupported) {
  67241. _this.dispose(camera);
  67242. }
  67243. _this.onActivate = null;
  67244. };
  67245. _this.onApplyObservable.add(function (effect) {
  67246. _this._updateMeshScreenCoordinates(scene);
  67247. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67248. effect.setFloat("exposure", _this.exposure);
  67249. effect.setFloat("decay", _this.decay);
  67250. effect.setFloat("weight", _this.weight);
  67251. effect.setFloat("density", _this.density);
  67252. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67253. });
  67254. return _this;
  67255. }
  67256. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67257. get: function () {
  67258. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67259. return false;
  67260. },
  67261. set: function (useDiffuseColor) {
  67262. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67263. },
  67264. enumerable: true,
  67265. configurable: true
  67266. });
  67267. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67268. return "VolumetricLightScatteringPostProcess";
  67269. };
  67270. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67271. var mesh = subMesh.getMesh();
  67272. // Render this.mesh as default
  67273. if (mesh === this.mesh && mesh.material) {
  67274. return mesh.material.isReady(mesh);
  67275. }
  67276. var defines = [];
  67277. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67278. var material = subMesh.getMaterial();
  67279. // Alpha test
  67280. if (material) {
  67281. if (material.needAlphaTesting()) {
  67282. defines.push("#define ALPHATEST");
  67283. }
  67284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67285. attribs.push(BABYLON.VertexBuffer.UVKind);
  67286. defines.push("#define UV1");
  67287. }
  67288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67290. defines.push("#define UV2");
  67291. }
  67292. }
  67293. // Bones
  67294. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67297. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67298. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67299. }
  67300. else {
  67301. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67302. }
  67303. // Instances
  67304. if (useInstances) {
  67305. defines.push("#define INSTANCES");
  67306. attribs.push("world0");
  67307. attribs.push("world1");
  67308. attribs.push("world2");
  67309. attribs.push("world3");
  67310. }
  67311. // Get correct effect
  67312. var join = defines.join("\n");
  67313. if (this._cachedDefines !== join) {
  67314. this._cachedDefines = join;
  67315. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67316. }
  67317. return this._volumetricLightScatteringPass.isReady();
  67318. };
  67319. /**
  67320. * Sets the new light position for light scattering effect
  67321. * @param {BABYLON.Vector3} The new custom light position
  67322. */
  67323. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67324. this.customMeshPosition = position;
  67325. };
  67326. /**
  67327. * Returns the light position for light scattering effect
  67328. * @return {BABYLON.Vector3} The custom light position
  67329. */
  67330. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67331. return this.customMeshPosition;
  67332. };
  67333. /**
  67334. * Disposes the internal assets and detaches the post-process from the camera
  67335. */
  67336. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67337. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67338. if (rttIndex !== -1) {
  67339. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67340. }
  67341. this._volumetricLightScatteringRTT.dispose();
  67342. _super.prototype.dispose.call(this, camera);
  67343. };
  67344. /**
  67345. * Returns the render target texture used by the post-process
  67346. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67347. */
  67348. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67349. return this._volumetricLightScatteringRTT;
  67350. };
  67351. // Private methods
  67352. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67353. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67354. return true;
  67355. }
  67356. return false;
  67357. };
  67358. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67359. var _this = this;
  67360. var engine = scene.getEngine();
  67361. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67362. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67363. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67364. this._volumetricLightScatteringRTT.renderList = null;
  67365. this._volumetricLightScatteringRTT.renderParticles = false;
  67366. var camera = this.getCamera();
  67367. if (camera) {
  67368. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67369. }
  67370. else {
  67371. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67372. }
  67373. // Custom render function for submeshes
  67374. var renderSubMesh = function (subMesh) {
  67375. var mesh = subMesh.getRenderingMesh();
  67376. if (_this._meshExcluded(mesh)) {
  67377. return;
  67378. }
  67379. var material = subMesh.getMaterial();
  67380. if (!material) {
  67381. return;
  67382. }
  67383. var scene = mesh.getScene();
  67384. var engine = scene.getEngine();
  67385. // Culling
  67386. engine.setState(material.backFaceCulling);
  67387. // Managing instances
  67388. var batch = mesh._getInstancesRenderList(subMesh._id);
  67389. if (batch.mustReturn) {
  67390. return;
  67391. }
  67392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67393. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67394. var effect = _this._volumetricLightScatteringPass;
  67395. if (mesh === _this.mesh) {
  67396. if (subMesh.effect) {
  67397. effect = subMesh.effect;
  67398. }
  67399. else {
  67400. effect = material.getEffect();
  67401. }
  67402. }
  67403. engine.enableEffect(effect);
  67404. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67405. if (mesh === _this.mesh) {
  67406. material.bind(mesh.getWorldMatrix(), mesh);
  67407. }
  67408. else {
  67409. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67410. // Alpha test
  67411. if (material && material.needAlphaTesting()) {
  67412. var alphaTexture = material.getAlphaTestTexture();
  67413. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67414. if (alphaTexture) {
  67415. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67416. }
  67417. }
  67418. // Bones
  67419. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67420. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67421. }
  67422. }
  67423. // Draw
  67424. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67425. }
  67426. };
  67427. // Render target texture callbacks
  67428. var savedSceneClearColor;
  67429. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67430. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67431. savedSceneClearColor = scene.clearColor;
  67432. scene.clearColor = sceneClearColor;
  67433. });
  67434. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67435. scene.clearColor = savedSceneClearColor;
  67436. });
  67437. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67438. var engine = scene.getEngine();
  67439. var index;
  67440. if (depthOnlySubMeshes.length) {
  67441. engine.setColorWrite(false);
  67442. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67443. renderSubMesh(depthOnlySubMeshes.data[index]);
  67444. }
  67445. engine.setColorWrite(true);
  67446. }
  67447. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67448. renderSubMesh(opaqueSubMeshes.data[index]);
  67449. }
  67450. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67451. renderSubMesh(alphaTestSubMeshes.data[index]);
  67452. }
  67453. if (transparentSubMeshes.length) {
  67454. // Sort sub meshes
  67455. for (index = 0; index < transparentSubMeshes.length; index++) {
  67456. var submesh = transparentSubMeshes.data[index];
  67457. var boundingInfo = submesh.getBoundingInfo();
  67458. if (boundingInfo && scene.activeCamera) {
  67459. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67460. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67461. }
  67462. }
  67463. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67464. sortedArray.sort(function (a, b) {
  67465. // Alpha index first
  67466. if (a._alphaIndex > b._alphaIndex) {
  67467. return 1;
  67468. }
  67469. if (a._alphaIndex < b._alphaIndex) {
  67470. return -1;
  67471. }
  67472. // Then distance to camera
  67473. if (a._distanceToCamera < b._distanceToCamera) {
  67474. return 1;
  67475. }
  67476. if (a._distanceToCamera > b._distanceToCamera) {
  67477. return -1;
  67478. }
  67479. return 0;
  67480. });
  67481. // Render sub meshes
  67482. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67483. for (index = 0; index < sortedArray.length; index++) {
  67484. renderSubMesh(sortedArray[index]);
  67485. }
  67486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67487. }
  67488. };
  67489. };
  67490. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67491. var transform = scene.getTransformMatrix();
  67492. var meshPosition;
  67493. if (this.useCustomMeshPosition) {
  67494. meshPosition = this.customMeshPosition;
  67495. }
  67496. else if (this.attachedNode) {
  67497. meshPosition = this.attachedNode.position;
  67498. }
  67499. else {
  67500. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67501. }
  67502. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67503. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67504. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67505. if (this.invert)
  67506. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67507. };
  67508. // Static methods
  67509. /**
  67510. * Creates a default mesh for the Volumeric Light Scattering post-process
  67511. * @param {string} The mesh name
  67512. * @param {BABYLON.Scene} The scene where to create the mesh
  67513. * @return {BABYLON.Mesh} the default mesh
  67514. */
  67515. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67516. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67517. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67518. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67519. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67520. mesh.material = material;
  67521. return mesh;
  67522. };
  67523. __decorate([
  67524. BABYLON.serializeAsVector3()
  67525. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67526. __decorate([
  67527. BABYLON.serialize()
  67528. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67529. __decorate([
  67530. BABYLON.serialize()
  67531. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67532. __decorate([
  67533. BABYLON.serializeAsMeshReference()
  67534. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67535. __decorate([
  67536. BABYLON.serialize()
  67537. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67538. __decorate([
  67539. BABYLON.serialize()
  67540. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67541. __decorate([
  67542. BABYLON.serialize()
  67543. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67544. __decorate([
  67545. BABYLON.serialize()
  67546. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67547. __decorate([
  67548. BABYLON.serialize()
  67549. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67550. return VolumetricLightScatteringPostProcess;
  67551. }(BABYLON.PostProcess));
  67552. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67553. })(BABYLON || (BABYLON = {}));
  67554. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67555. //
  67556. // This post-process allows the modification of rendered colors by using
  67557. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67558. //
  67559. // The object needs to be provided an url to a texture containing the color
  67560. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67561. // Use an image editing software to tweak the LUT to match your needs.
  67562. //
  67563. // For an example of a color LUT, see here:
  67564. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67565. // For explanations on color grading, see here:
  67566. // http://udn.epicgames.com/Three/ColorGrading.html
  67567. //
  67568. var BABYLON;
  67569. (function (BABYLON) {
  67570. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67571. __extends(ColorCorrectionPostProcess, _super);
  67572. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67573. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67574. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67575. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67576. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67577. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67578. _this.onApply = function (effect) {
  67579. effect.setTexture("colorTable", _this._colorTableTexture);
  67580. };
  67581. return _this;
  67582. }
  67583. return ColorCorrectionPostProcess;
  67584. }(BABYLON.PostProcess));
  67585. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67586. })(BABYLON || (BABYLON = {}));
  67587. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67588. var BABYLON;
  67589. (function (BABYLON) {
  67590. var TonemappingOperator;
  67591. (function (TonemappingOperator) {
  67592. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67593. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67594. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67595. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67596. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67597. ;
  67598. var TonemapPostProcess = /** @class */ (function (_super) {
  67599. __extends(TonemapPostProcess, _super);
  67600. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67602. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67603. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67604. _this._operator = _operator;
  67605. _this.exposureAdjustment = exposureAdjustment;
  67606. var defines = "#define ";
  67607. if (_this._operator === TonemappingOperator.Hable)
  67608. defines += "HABLE_TONEMAPPING";
  67609. else if (_this._operator === TonemappingOperator.Reinhard)
  67610. defines += "REINHARD_TONEMAPPING";
  67611. else if (_this._operator === TonemappingOperator.HejiDawson)
  67612. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67613. else if (_this._operator === TonemappingOperator.Photographic)
  67614. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67615. //sadly a second call to create the effect.
  67616. _this.updateEffect(defines);
  67617. _this.onApply = function (effect) {
  67618. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67619. };
  67620. return _this;
  67621. }
  67622. return TonemapPostProcess;
  67623. }(BABYLON.PostProcess));
  67624. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67625. })(BABYLON || (BABYLON = {}));
  67626. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67627. var BABYLON;
  67628. (function (BABYLON) {
  67629. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67630. __extends(DisplayPassPostProcess, _super);
  67631. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67632. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67633. }
  67634. return DisplayPassPostProcess;
  67635. }(BABYLON.PostProcess));
  67636. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67637. })(BABYLON || (BABYLON = {}));
  67638. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67639. var BABYLON;
  67640. (function (BABYLON) {
  67641. var HighlightsPostProcess = /** @class */ (function (_super) {
  67642. __extends(HighlightsPostProcess, _super);
  67643. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67644. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67645. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67646. }
  67647. return HighlightsPostProcess;
  67648. }(BABYLON.PostProcess));
  67649. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67650. })(BABYLON || (BABYLON = {}));
  67651. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67652. var BABYLON;
  67653. (function (BABYLON) {
  67654. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67655. __extends(ImageProcessingPostProcess, _super);
  67656. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67657. if (camera === void 0) { camera = null; }
  67658. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67659. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67660. _this._fromLinearSpace = true;
  67661. /**
  67662. * Defines cache preventing GC.
  67663. */
  67664. _this._defines = {
  67665. IMAGEPROCESSING: false,
  67666. VIGNETTE: false,
  67667. VIGNETTEBLENDMODEMULTIPLY: false,
  67668. VIGNETTEBLENDMODEOPAQUE: false,
  67669. TONEMAPPING: false,
  67670. CONTRAST: false,
  67671. COLORCURVES: false,
  67672. COLORGRADING: false,
  67673. COLORGRADING3D: false,
  67674. FROMLINEARSPACE: false,
  67675. SAMPLER3DGREENDEPTH: false,
  67676. SAMPLER3DBGRMAP: false,
  67677. IMAGEPROCESSINGPOSTPROCESS: false,
  67678. EXPOSURE: false,
  67679. };
  67680. // Setup the configuration as forced by the constructor. This would then not force the
  67681. // scene materials output in linear space and let untouched the default forward pass.
  67682. if (imageProcessingConfiguration) {
  67683. imageProcessingConfiguration.applyByPostProcess = true;
  67684. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67685. // This will cause the shader to be compiled
  67686. _this.fromLinearSpace = false;
  67687. }
  67688. else {
  67689. _this._attachImageProcessingConfiguration(null, true);
  67690. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67691. }
  67692. _this.onApply = function (effect) {
  67693. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67694. };
  67695. return _this;
  67696. }
  67697. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67698. /**
  67699. * Gets the image processing configuration used either in this material.
  67700. */
  67701. get: function () {
  67702. return this._imageProcessingConfiguration;
  67703. },
  67704. /**
  67705. * Sets the Default image processing configuration used either in the this material.
  67706. *
  67707. * If sets to null, the scene one is in use.
  67708. */
  67709. set: function (value) {
  67710. this._attachImageProcessingConfiguration(value);
  67711. },
  67712. enumerable: true,
  67713. configurable: true
  67714. });
  67715. /**
  67716. * Attaches a new image processing configuration to the PBR Material.
  67717. * @param configuration
  67718. */
  67719. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67720. var _this = this;
  67721. if (doNotBuild === void 0) { doNotBuild = false; }
  67722. if (configuration === this._imageProcessingConfiguration) {
  67723. return;
  67724. }
  67725. // Detaches observer.
  67726. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67727. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67728. }
  67729. // Pick the scene configuration if needed.
  67730. if (!configuration) {
  67731. var scene = null;
  67732. var engine = this.getEngine();
  67733. var camera = this.getCamera();
  67734. if (camera) {
  67735. scene = camera.getScene();
  67736. }
  67737. else if (engine && engine.scenes) {
  67738. var scenes = engine.scenes;
  67739. scene = scenes[scenes.length - 1];
  67740. }
  67741. else {
  67742. scene = BABYLON.Engine.LastCreatedScene;
  67743. }
  67744. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67745. }
  67746. else {
  67747. this._imageProcessingConfiguration = configuration;
  67748. }
  67749. // Attaches observer.
  67750. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67751. _this._updateParameters();
  67752. });
  67753. // Ensure the effect will be rebuilt.
  67754. if (!doNotBuild) {
  67755. this._updateParameters();
  67756. }
  67757. };
  67758. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67759. /**
  67760. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67761. */
  67762. get: function () {
  67763. return this.imageProcessingConfiguration.colorCurves;
  67764. },
  67765. /**
  67766. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67767. */
  67768. set: function (value) {
  67769. this.imageProcessingConfiguration.colorCurves = value;
  67770. },
  67771. enumerable: true,
  67772. configurable: true
  67773. });
  67774. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67775. /**
  67776. * Gets wether the color curves effect is enabled.
  67777. */
  67778. get: function () {
  67779. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67780. },
  67781. /**
  67782. * Sets wether the color curves effect is enabled.
  67783. */
  67784. set: function (value) {
  67785. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67786. },
  67787. enumerable: true,
  67788. configurable: true
  67789. });
  67790. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67791. /**
  67792. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67793. */
  67794. get: function () {
  67795. return this.imageProcessingConfiguration.colorGradingTexture;
  67796. },
  67797. /**
  67798. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67799. */
  67800. set: function (value) {
  67801. this.imageProcessingConfiguration.colorGradingTexture = value;
  67802. },
  67803. enumerable: true,
  67804. configurable: true
  67805. });
  67806. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67807. /**
  67808. * Gets wether the color grading effect is enabled.
  67809. */
  67810. get: function () {
  67811. return this.imageProcessingConfiguration.colorGradingEnabled;
  67812. },
  67813. /**
  67814. * Gets wether the color grading effect is enabled.
  67815. */
  67816. set: function (value) {
  67817. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67818. },
  67819. enumerable: true,
  67820. configurable: true
  67821. });
  67822. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67823. /**
  67824. * Gets exposure used in the effect.
  67825. */
  67826. get: function () {
  67827. return this.imageProcessingConfiguration.exposure;
  67828. },
  67829. /**
  67830. * Sets exposure used in the effect.
  67831. */
  67832. set: function (value) {
  67833. this.imageProcessingConfiguration.exposure = value;
  67834. },
  67835. enumerable: true,
  67836. configurable: true
  67837. });
  67838. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67839. /**
  67840. * Gets wether tonemapping is enabled or not.
  67841. */
  67842. get: function () {
  67843. return this._imageProcessingConfiguration.toneMappingEnabled;
  67844. },
  67845. /**
  67846. * Sets wether tonemapping is enabled or not
  67847. */
  67848. set: function (value) {
  67849. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67850. },
  67851. enumerable: true,
  67852. configurable: true
  67853. });
  67854. ;
  67855. ;
  67856. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67857. /**
  67858. * Gets contrast used in the effect.
  67859. */
  67860. get: function () {
  67861. return this.imageProcessingConfiguration.contrast;
  67862. },
  67863. /**
  67864. * Sets contrast used in the effect.
  67865. */
  67866. set: function (value) {
  67867. this.imageProcessingConfiguration.contrast = value;
  67868. },
  67869. enumerable: true,
  67870. configurable: true
  67871. });
  67872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67873. /**
  67874. * Gets Vignette stretch size.
  67875. */
  67876. get: function () {
  67877. return this.imageProcessingConfiguration.vignetteStretch;
  67878. },
  67879. /**
  67880. * Sets Vignette stretch size.
  67881. */
  67882. set: function (value) {
  67883. this.imageProcessingConfiguration.vignetteStretch = value;
  67884. },
  67885. enumerable: true,
  67886. configurable: true
  67887. });
  67888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  67889. /**
  67890. * Gets Vignette centre X Offset.
  67891. */
  67892. get: function () {
  67893. return this.imageProcessingConfiguration.vignetteCentreX;
  67894. },
  67895. /**
  67896. * Sets Vignette centre X Offset.
  67897. */
  67898. set: function (value) {
  67899. this.imageProcessingConfiguration.vignetteCentreX = value;
  67900. },
  67901. enumerable: true,
  67902. configurable: true
  67903. });
  67904. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  67905. /**
  67906. * Gets Vignette centre Y Offset.
  67907. */
  67908. get: function () {
  67909. return this.imageProcessingConfiguration.vignetteCentreY;
  67910. },
  67911. /**
  67912. * Sets Vignette centre Y Offset.
  67913. */
  67914. set: function (value) {
  67915. this.imageProcessingConfiguration.vignetteCentreY = value;
  67916. },
  67917. enumerable: true,
  67918. configurable: true
  67919. });
  67920. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  67921. /**
  67922. * Gets Vignette weight or intensity of the vignette effect.
  67923. */
  67924. get: function () {
  67925. return this.imageProcessingConfiguration.vignetteWeight;
  67926. },
  67927. /**
  67928. * Sets Vignette weight or intensity of the vignette effect.
  67929. */
  67930. set: function (value) {
  67931. this.imageProcessingConfiguration.vignetteWeight = value;
  67932. },
  67933. enumerable: true,
  67934. configurable: true
  67935. });
  67936. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  67937. /**
  67938. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67939. * if vignetteEnabled is set to true.
  67940. */
  67941. get: function () {
  67942. return this.imageProcessingConfiguration.vignetteColor;
  67943. },
  67944. /**
  67945. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67946. * if vignetteEnabled is set to true.
  67947. */
  67948. set: function (value) {
  67949. this.imageProcessingConfiguration.vignetteColor = value;
  67950. },
  67951. enumerable: true,
  67952. configurable: true
  67953. });
  67954. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  67955. /**
  67956. * Gets Camera field of view used by the Vignette effect.
  67957. */
  67958. get: function () {
  67959. return this.imageProcessingConfiguration.vignetteCameraFov;
  67960. },
  67961. /**
  67962. * Sets Camera field of view used by the Vignette effect.
  67963. */
  67964. set: function (value) {
  67965. this.imageProcessingConfiguration.vignetteCameraFov = value;
  67966. },
  67967. enumerable: true,
  67968. configurable: true
  67969. });
  67970. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  67971. /**
  67972. * Gets the vignette blend mode allowing different kind of effect.
  67973. */
  67974. get: function () {
  67975. return this.imageProcessingConfiguration.vignetteBlendMode;
  67976. },
  67977. /**
  67978. * Sets the vignette blend mode allowing different kind of effect.
  67979. */
  67980. set: function (value) {
  67981. this.imageProcessingConfiguration.vignetteBlendMode = value;
  67982. },
  67983. enumerable: true,
  67984. configurable: true
  67985. });
  67986. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  67987. /**
  67988. * Gets wether the vignette effect is enabled.
  67989. */
  67990. get: function () {
  67991. return this.imageProcessingConfiguration.vignetteEnabled;
  67992. },
  67993. /**
  67994. * Sets wether the vignette effect is enabled.
  67995. */
  67996. set: function (value) {
  67997. this.imageProcessingConfiguration.vignetteEnabled = value;
  67998. },
  67999. enumerable: true,
  68000. configurable: true
  68001. });
  68002. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68003. /**
  68004. * Gets wether the input of the processing is in Gamma or Linear Space.
  68005. */
  68006. get: function () {
  68007. return this._fromLinearSpace;
  68008. },
  68009. /**
  68010. * Sets wether the input of the processing is in Gamma or Linear Space.
  68011. */
  68012. set: function (value) {
  68013. if (this._fromLinearSpace === value) {
  68014. return;
  68015. }
  68016. this._fromLinearSpace = value;
  68017. this._updateParameters();
  68018. },
  68019. enumerable: true,
  68020. configurable: true
  68021. });
  68022. ImageProcessingPostProcess.prototype.getClassName = function () {
  68023. return "ImageProcessingPostProcess";
  68024. };
  68025. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68026. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68027. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68028. var defines = "";
  68029. for (var define in this._defines) {
  68030. if (this._defines[define]) {
  68031. defines += "#define " + define + ";\r\n";
  68032. }
  68033. }
  68034. var samplers = ["textureSampler"];
  68035. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68036. var uniforms = ["scale"];
  68037. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68038. this.updateEffect(defines, uniforms, samplers);
  68039. };
  68040. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68041. _super.prototype.dispose.call(this, camera);
  68042. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68043. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68044. }
  68045. this.imageProcessingConfiguration.applyByPostProcess = false;
  68046. };
  68047. __decorate([
  68048. BABYLON.serialize()
  68049. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68050. return ImageProcessingPostProcess;
  68051. }(BABYLON.PostProcess));
  68052. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68053. })(BABYLON || (BABYLON = {}));
  68054. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68055. var BABYLON;
  68056. (function (BABYLON) {
  68057. /**
  68058. * The Blur Post Process which blurs an image based on a kernel and direction.
  68059. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68060. */
  68061. var BlurPostProcess = /** @class */ (function (_super) {
  68062. __extends(BlurPostProcess, _super);
  68063. /**
  68064. * Creates a new instance of @see BlurPostProcess
  68065. * @param name The name of the effect.
  68066. * @param direction The direction in which to blur the image.
  68067. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  68068. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68069. * @param camera The camera to apply the render pass to.
  68070. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68071. * @param engine The engine which the post process will be applied. (default: current engine)
  68072. * @param reusable If the post process can be reused on the same frame. (default: false)
  68073. * @param textureType Type of textures used when performing the post process. (default: 0)
  68074. */
  68075. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68078. if (defines === void 0) { defines = ""; }
  68079. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68080. _this.direction = direction;
  68081. _this._packedFloat = false;
  68082. _this._staticDefines = "";
  68083. _this._staticDefines = defines;
  68084. _this.onApplyObservable.add(function (effect) {
  68085. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68086. });
  68087. _this.kernel = kernel;
  68088. return _this;
  68089. }
  68090. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68091. /**
  68092. * Gets the length in pixels of the blur sample region
  68093. */
  68094. get: function () {
  68095. return this._idealKernel;
  68096. },
  68097. /**
  68098. * Sets the length in pixels of the blur sample region
  68099. */
  68100. set: function (v) {
  68101. if (this._idealKernel === v) {
  68102. return;
  68103. }
  68104. v = Math.max(v, 1);
  68105. this._idealKernel = v;
  68106. this._kernel = this._nearestBestKernel(v);
  68107. this._updateParameters();
  68108. },
  68109. enumerable: true,
  68110. configurable: true
  68111. });
  68112. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68113. /**
  68114. * Gets wether or not the blur is unpacking/repacking floats
  68115. */
  68116. get: function () {
  68117. return this._packedFloat;
  68118. },
  68119. /**
  68120. * Sets wether or not the blur needs to unpack/repack floats
  68121. */
  68122. set: function (v) {
  68123. if (this._packedFloat === v) {
  68124. return;
  68125. }
  68126. this._packedFloat = v;
  68127. this._updateParameters();
  68128. },
  68129. enumerable: true,
  68130. configurable: true
  68131. });
  68132. BlurPostProcess.prototype._updateParameters = function () {
  68133. // Generate sampling offsets and weights
  68134. var N = this._kernel;
  68135. var centerIndex = (N - 1) / 2;
  68136. // Generate Gaussian sampling weights over kernel
  68137. var offsets = [];
  68138. var weights = [];
  68139. var totalWeight = 0;
  68140. for (var i = 0; i < N; i++) {
  68141. var u = i / (N - 1);
  68142. var w = this._gaussianWeight(u * 2.0 - 1);
  68143. offsets[i] = (i - centerIndex);
  68144. weights[i] = w;
  68145. totalWeight += w;
  68146. }
  68147. // Normalize weights
  68148. for (var i = 0; i < weights.length; i++) {
  68149. weights[i] /= totalWeight;
  68150. }
  68151. // Optimize: combine samples to take advantage of hardware linear sampling
  68152. // Walk from left to center, combining pairs (symmetrically)
  68153. var linearSamplingWeights = [];
  68154. var linearSamplingOffsets = [];
  68155. var linearSamplingMap = [];
  68156. for (var i = 0; i <= centerIndex; i += 2) {
  68157. var j = Math.min(i + 1, Math.floor(centerIndex));
  68158. var singleCenterSample = i === j;
  68159. if (singleCenterSample) {
  68160. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68161. }
  68162. else {
  68163. var sharedCell = j === centerIndex;
  68164. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68165. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68166. if (offsetLinear === 0) {
  68167. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68168. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68169. }
  68170. else {
  68171. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68172. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68173. }
  68174. }
  68175. }
  68176. for (var i = 0; i < linearSamplingMap.length; i++) {
  68177. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68178. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68179. }
  68180. // Replace with optimized
  68181. offsets = linearSamplingOffsets;
  68182. weights = linearSamplingWeights;
  68183. // Generate shaders
  68184. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68185. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68186. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68187. var defines = "";
  68188. defines += this._staticDefines;
  68189. for (var i = 0; i < varyingCount; i++) {
  68190. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68191. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68192. }
  68193. var depCount = 0;
  68194. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68195. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68196. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68197. depCount++;
  68198. }
  68199. if (this.packedFloat) {
  68200. defines += "#define PACKEDFLOAT 1";
  68201. }
  68202. this.updateEffect(defines, null, null, {
  68203. varyingCount: varyingCount,
  68204. depCount: depCount
  68205. });
  68206. };
  68207. /**
  68208. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68209. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68210. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68211. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68212. * The gaps between physical kernels are compensated for in the weighting of the samples
  68213. * @param idealKernel Ideal blur kernel.
  68214. * @return Nearest best kernel.
  68215. */
  68216. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68217. var v = Math.round(idealKernel);
  68218. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68219. var k = _a[_i];
  68220. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68221. return Math.max(k, 3);
  68222. }
  68223. }
  68224. return Math.max(v, 3);
  68225. };
  68226. /**
  68227. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68228. * @param x The point on the Gaussian distribution to sample.
  68229. * @return the value of the Gaussian function at x.
  68230. */
  68231. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68232. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68233. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68234. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68235. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68236. // truncated at around 1.3% of peak strength.
  68237. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68238. var sigma = (1 / 3);
  68239. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68240. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68241. var weight = (1.0 / denominator) * Math.exp(exponent);
  68242. return weight;
  68243. };
  68244. /**
  68245. * Generates a string that can be used as a floating point number in GLSL.
  68246. * @param x Value to print.
  68247. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68248. * @return GLSL float string.
  68249. */
  68250. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68251. if (decimalFigures === void 0) { decimalFigures = 8; }
  68252. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68253. };
  68254. return BlurPostProcess;
  68255. }(BABYLON.PostProcess));
  68256. BABYLON.BlurPostProcess = BlurPostProcess;
  68257. })(BABYLON || (BABYLON = {}));
  68258. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68259. var BABYLON;
  68260. (function (BABYLON) {
  68261. var Bone = /** @class */ (function (_super) {
  68262. __extends(Bone, _super);
  68263. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68264. if (parentBone === void 0) { parentBone = null; }
  68265. if (localMatrix === void 0) { localMatrix = null; }
  68266. if (restPose === void 0) { restPose = null; }
  68267. if (baseMatrix === void 0) { baseMatrix = null; }
  68268. if (index === void 0) { index = null; }
  68269. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68270. _this.name = name;
  68271. _this.children = new Array();
  68272. _this.animations = new Array();
  68273. // Set this value to map this bone to a different index in the transform matrices.
  68274. // Set this value to -1 to exclude the bone from the transform matrices.
  68275. _this._index = null;
  68276. _this._worldTransform = new BABYLON.Matrix();
  68277. _this._absoluteTransform = new BABYLON.Matrix();
  68278. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68279. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68280. _this._scaleVector = BABYLON.Vector3.One();
  68281. _this._negateScaleChildren = BABYLON.Vector3.One();
  68282. _this._scalingDeterminant = 1;
  68283. _this._skeleton = skeleton;
  68284. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68285. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68286. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68287. _this._index = index;
  68288. skeleton.bones.push(_this);
  68289. _this.setParent(parentBone, false);
  68290. _this._updateDifferenceMatrix();
  68291. return _this;
  68292. }
  68293. Object.defineProperty(Bone.prototype, "_matrix", {
  68294. get: function () {
  68295. return this._localMatrix;
  68296. },
  68297. set: function (val) {
  68298. if (this._localMatrix) {
  68299. this._localMatrix.copyFrom(val);
  68300. }
  68301. else {
  68302. this._localMatrix = val;
  68303. }
  68304. },
  68305. enumerable: true,
  68306. configurable: true
  68307. });
  68308. // Members
  68309. Bone.prototype.getSkeleton = function () {
  68310. return this._skeleton;
  68311. };
  68312. Bone.prototype.getParent = function () {
  68313. return this._parent;
  68314. };
  68315. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68316. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68317. if (this._parent === parent) {
  68318. return;
  68319. }
  68320. if (this._parent) {
  68321. var index = this._parent.children.indexOf(this);
  68322. if (index !== -1) {
  68323. this._parent.children.splice(index, 1);
  68324. }
  68325. }
  68326. this._parent = parent;
  68327. if (this._parent) {
  68328. this._parent.children.push(this);
  68329. }
  68330. if (updateDifferenceMatrix) {
  68331. this._updateDifferenceMatrix();
  68332. }
  68333. };
  68334. Bone.prototype.getLocalMatrix = function () {
  68335. return this._localMatrix;
  68336. };
  68337. Bone.prototype.getBaseMatrix = function () {
  68338. return this._baseMatrix;
  68339. };
  68340. Bone.prototype.getRestPose = function () {
  68341. return this._restPose;
  68342. };
  68343. Bone.prototype.returnToRest = function () {
  68344. this.updateMatrix(this._restPose.clone());
  68345. };
  68346. Bone.prototype.getWorldMatrix = function () {
  68347. return this._worldTransform;
  68348. };
  68349. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68350. return this._invertedAbsoluteTransform;
  68351. };
  68352. Bone.prototype.getAbsoluteTransform = function () {
  68353. return this._absoluteTransform;
  68354. };
  68355. Object.defineProperty(Bone.prototype, "position", {
  68356. // Properties (matches AbstractMesh properties)
  68357. get: function () {
  68358. return this.getPosition();
  68359. },
  68360. set: function (newPosition) {
  68361. this.setPosition(newPosition);
  68362. },
  68363. enumerable: true,
  68364. configurable: true
  68365. });
  68366. Object.defineProperty(Bone.prototype, "rotation", {
  68367. get: function () {
  68368. return this.getRotation();
  68369. },
  68370. set: function (newRotation) {
  68371. this.setRotation(newRotation);
  68372. },
  68373. enumerable: true,
  68374. configurable: true
  68375. });
  68376. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68377. get: function () {
  68378. return this.getRotationQuaternion();
  68379. },
  68380. set: function (newRotation) {
  68381. this.setRotationQuaternion(newRotation);
  68382. },
  68383. enumerable: true,
  68384. configurable: true
  68385. });
  68386. Object.defineProperty(Bone.prototype, "scaling", {
  68387. get: function () {
  68388. return this.getScale();
  68389. },
  68390. set: function (newScaling) {
  68391. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68392. },
  68393. enumerable: true,
  68394. configurable: true
  68395. });
  68396. // Methods
  68397. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68398. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68399. this._baseMatrix = matrix.clone();
  68400. this._localMatrix = matrix.clone();
  68401. this._skeleton._markAsDirty();
  68402. if (updateDifferenceMatrix) {
  68403. this._updateDifferenceMatrix();
  68404. }
  68405. };
  68406. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68407. if (!rootMatrix) {
  68408. rootMatrix = this._baseMatrix;
  68409. }
  68410. if (this._parent) {
  68411. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68412. }
  68413. else {
  68414. this._absoluteTransform.copyFrom(rootMatrix);
  68415. }
  68416. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68417. for (var index = 0; index < this.children.length; index++) {
  68418. this.children[index]._updateDifferenceMatrix();
  68419. }
  68420. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68421. };
  68422. Bone.prototype.markAsDirty = function () {
  68423. this._currentRenderId++;
  68424. this._skeleton._markAsDirty();
  68425. };
  68426. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68427. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68428. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68429. // all animation may be coming from a library skeleton, so may need to create animation
  68430. if (this.animations.length === 0) {
  68431. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68432. this.animations[0].setKeys([]);
  68433. }
  68434. // get animation info / verify there is such a range from the source bone
  68435. var sourceRange = source.animations[0].getRange(rangeName);
  68436. if (!sourceRange) {
  68437. return false;
  68438. }
  68439. var from = sourceRange.from;
  68440. var to = sourceRange.to;
  68441. var sourceKeys = source.animations[0].getKeys();
  68442. // rescaling prep
  68443. var sourceBoneLength = source.length;
  68444. var sourceParent = source.getParent();
  68445. var parent = this.getParent();
  68446. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68447. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68448. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68449. var destKeys = this.animations[0].getKeys();
  68450. // loop vars declaration
  68451. var orig;
  68452. var origTranslation;
  68453. var mat;
  68454. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68455. orig = sourceKeys[key];
  68456. if (orig.frame >= from && orig.frame <= to) {
  68457. if (rescaleAsRequired) {
  68458. mat = orig.value.clone();
  68459. // scale based on parent ratio, when bone has parent
  68460. if (parentScalingReqd) {
  68461. origTranslation = mat.getTranslation();
  68462. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68463. // scale based on skeleton dimension ratio when root bone, and value is passed
  68464. }
  68465. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68466. origTranslation = mat.getTranslation();
  68467. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68468. // use original when root bone, and no data for skelDimensionsRatio
  68469. }
  68470. else {
  68471. mat = orig.value;
  68472. }
  68473. }
  68474. else {
  68475. mat = orig.value;
  68476. }
  68477. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68478. }
  68479. }
  68480. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68481. return true;
  68482. };
  68483. /**
  68484. * Translate the bone in local or world space.
  68485. * @param vec The amount to translate the bone.
  68486. * @param space The space that the translation is in.
  68487. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68488. */
  68489. Bone.prototype.translate = function (vec, space, mesh) {
  68490. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68491. var lm = this.getLocalMatrix();
  68492. if (space == BABYLON.Space.LOCAL) {
  68493. lm.m[12] += vec.x;
  68494. lm.m[13] += vec.y;
  68495. lm.m[14] += vec.z;
  68496. }
  68497. else {
  68498. var wm = null;
  68499. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68500. if (mesh) {
  68501. wm = mesh.getWorldMatrix();
  68502. }
  68503. this._skeleton.computeAbsoluteTransforms();
  68504. var tmat = Bone._tmpMats[0];
  68505. var tvec = Bone._tmpVecs[0];
  68506. if (this._parent) {
  68507. if (mesh && wm) {
  68508. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68509. tmat.multiplyToRef(wm, tmat);
  68510. }
  68511. else {
  68512. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68513. }
  68514. }
  68515. tmat.m[12] = 0;
  68516. tmat.m[13] = 0;
  68517. tmat.m[14] = 0;
  68518. tmat.invert();
  68519. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68520. lm.m[12] += tvec.x;
  68521. lm.m[13] += tvec.y;
  68522. lm.m[14] += tvec.z;
  68523. }
  68524. this.markAsDirty();
  68525. };
  68526. /**
  68527. * Set the postion of the bone in local or world space.
  68528. * @param position The position to set the bone.
  68529. * @param space The space that the position is in.
  68530. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68531. */
  68532. Bone.prototype.setPosition = function (position, space, mesh) {
  68533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68534. var lm = this.getLocalMatrix();
  68535. if (space == BABYLON.Space.LOCAL) {
  68536. lm.m[12] = position.x;
  68537. lm.m[13] = position.y;
  68538. lm.m[14] = position.z;
  68539. }
  68540. else {
  68541. var wm = null;
  68542. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68543. if (mesh) {
  68544. wm = mesh.getWorldMatrix();
  68545. }
  68546. this._skeleton.computeAbsoluteTransforms();
  68547. var tmat = Bone._tmpMats[0];
  68548. var vec = Bone._tmpVecs[0];
  68549. if (this._parent) {
  68550. if (mesh && wm) {
  68551. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68552. tmat.multiplyToRef(wm, tmat);
  68553. }
  68554. else {
  68555. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68556. }
  68557. }
  68558. tmat.invert();
  68559. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68560. lm.m[12] = vec.x;
  68561. lm.m[13] = vec.y;
  68562. lm.m[14] = vec.z;
  68563. }
  68564. this.markAsDirty();
  68565. };
  68566. /**
  68567. * Set the absolute postion of the bone (world space).
  68568. * @param position The position to set the bone.
  68569. * @param mesh The mesh that this bone is attached to.
  68570. */
  68571. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68572. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68573. };
  68574. /**
  68575. * Set the scale of the bone on the x, y and z axes.
  68576. * @param x The scale of the bone on the x axis.
  68577. * @param x The scale of the bone on the y axis.
  68578. * @param z The scale of the bone on the z axis.
  68579. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68580. */
  68581. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68582. if (scaleChildren === void 0) { scaleChildren = false; }
  68583. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68584. if (!scaleChildren) {
  68585. this._negateScaleChildren.x = 1 / x;
  68586. this._negateScaleChildren.y = 1 / y;
  68587. this._negateScaleChildren.z = 1 / z;
  68588. }
  68589. this._syncScaleVector();
  68590. }
  68591. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68592. };
  68593. /**
  68594. * Scale the bone on the x, y and z axes.
  68595. * @param x The amount to scale the bone on the x axis.
  68596. * @param x The amount to scale the bone on the y axis.
  68597. * @param z The amount to scale the bone on the z axis.
  68598. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68599. */
  68600. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68601. if (scaleChildren === void 0) { scaleChildren = false; }
  68602. var locMat = this.getLocalMatrix();
  68603. var origLocMat = Bone._tmpMats[0];
  68604. origLocMat.copyFrom(locMat);
  68605. var origLocMatInv = Bone._tmpMats[1];
  68606. origLocMatInv.copyFrom(origLocMat);
  68607. origLocMatInv.invert();
  68608. var scaleMat = Bone._tmpMats[2];
  68609. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68610. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68611. this._scaleVector.x *= x;
  68612. this._scaleVector.y *= y;
  68613. this._scaleVector.z *= z;
  68614. locMat.multiplyToRef(origLocMatInv, locMat);
  68615. locMat.multiplyToRef(scaleMat, locMat);
  68616. locMat.multiplyToRef(origLocMat, locMat);
  68617. var parent = this.getParent();
  68618. if (parent) {
  68619. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68620. }
  68621. else {
  68622. this.getAbsoluteTransform().copyFrom(locMat);
  68623. }
  68624. var len = this.children.length;
  68625. scaleMat.invert();
  68626. for (var i = 0; i < len; i++) {
  68627. var child = this.children[i];
  68628. var cm = child.getLocalMatrix();
  68629. cm.multiplyToRef(scaleMat, cm);
  68630. var lm = child.getLocalMatrix();
  68631. lm.m[12] *= x;
  68632. lm.m[13] *= y;
  68633. lm.m[14] *= z;
  68634. }
  68635. this.computeAbsoluteTransforms();
  68636. if (scaleChildren) {
  68637. for (var i = 0; i < len; i++) {
  68638. this.children[i].scale(x, y, z, scaleChildren);
  68639. }
  68640. }
  68641. this.markAsDirty();
  68642. };
  68643. /**
  68644. * Set the yaw, pitch, and roll of the bone in local or world space.
  68645. * @param yaw The rotation of the bone on the y axis.
  68646. * @param pitch The rotation of the bone on the x axis.
  68647. * @param roll The rotation of the bone on the z axis.
  68648. * @param space The space that the axes of rotation are in.
  68649. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68650. */
  68651. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68653. var rotMat = Bone._tmpMats[0];
  68654. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68655. var rotMatInv = Bone._tmpMats[1];
  68656. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68657. rotMatInv.multiplyToRef(rotMat, rotMat);
  68658. this._rotateWithMatrix(rotMat, space, mesh);
  68659. };
  68660. /**
  68661. * Rotate the bone on an axis in local or world space.
  68662. * @param axis The axis to rotate the bone on.
  68663. * @param amount The amount to rotate the bone.
  68664. * @param space The space that the axis is in.
  68665. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68666. */
  68667. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68668. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68669. var rmat = Bone._tmpMats[0];
  68670. rmat.m[12] = 0;
  68671. rmat.m[13] = 0;
  68672. rmat.m[14] = 0;
  68673. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68674. this._rotateWithMatrix(rmat, space, mesh);
  68675. };
  68676. /**
  68677. * Set the rotation of the bone to a particular axis angle in local or world space.
  68678. * @param axis The axis to rotate the bone on.
  68679. * @param angle The angle that the bone should be rotated to.
  68680. * @param space The space that the axis is in.
  68681. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68682. */
  68683. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68684. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68685. var rotMat = Bone._tmpMats[0];
  68686. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68687. var rotMatInv = Bone._tmpMats[1];
  68688. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68689. rotMatInv.multiplyToRef(rotMat, rotMat);
  68690. this._rotateWithMatrix(rotMat, space, mesh);
  68691. };
  68692. /**
  68693. * Set the euler rotation of the bone in local of world space.
  68694. * @param rotation The euler rotation that the bone should be set to.
  68695. * @param space The space that the rotation is in.
  68696. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68697. */
  68698. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68700. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68701. };
  68702. /**
  68703. * Set the quaternion rotation of the bone in local of world space.
  68704. * @param quat The quaternion rotation that the bone should be set to.
  68705. * @param space The space that the rotation is in.
  68706. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68707. */
  68708. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68709. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68710. var rotMatInv = Bone._tmpMats[0];
  68711. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68712. var rotMat = Bone._tmpMats[1];
  68713. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68714. rotMatInv.multiplyToRef(rotMat, rotMat);
  68715. this._rotateWithMatrix(rotMat, space, mesh);
  68716. };
  68717. /**
  68718. * Set the rotation matrix of the bone in local of world space.
  68719. * @param rotMat The rotation matrix that the bone should be set to.
  68720. * @param space The space that the rotation is in.
  68721. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68722. */
  68723. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68724. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68725. var rotMatInv = Bone._tmpMats[0];
  68726. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68727. var rotMat2 = Bone._tmpMats[1];
  68728. rotMat2.copyFrom(rotMat);
  68729. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68730. this._rotateWithMatrix(rotMat2, space, mesh);
  68731. };
  68732. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68734. var lmat = this.getLocalMatrix();
  68735. var lx = lmat.m[12];
  68736. var ly = lmat.m[13];
  68737. var lz = lmat.m[14];
  68738. var parent = this.getParent();
  68739. var parentScale = Bone._tmpMats[3];
  68740. var parentScaleInv = Bone._tmpMats[4];
  68741. if (parent) {
  68742. if (space == BABYLON.Space.WORLD) {
  68743. if (mesh) {
  68744. parentScale.copyFrom(mesh.getWorldMatrix());
  68745. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68746. }
  68747. else {
  68748. parentScale.copyFrom(parent.getAbsoluteTransform());
  68749. }
  68750. }
  68751. else {
  68752. parentScale = parent._scaleMatrix;
  68753. }
  68754. parentScaleInv.copyFrom(parentScale);
  68755. parentScaleInv.invert();
  68756. lmat.multiplyToRef(parentScale, lmat);
  68757. lmat.multiplyToRef(rmat, lmat);
  68758. lmat.multiplyToRef(parentScaleInv, lmat);
  68759. }
  68760. else {
  68761. if (space == BABYLON.Space.WORLD && mesh) {
  68762. parentScale.copyFrom(mesh.getWorldMatrix());
  68763. parentScaleInv.copyFrom(parentScale);
  68764. parentScaleInv.invert();
  68765. lmat.multiplyToRef(parentScale, lmat);
  68766. lmat.multiplyToRef(rmat, lmat);
  68767. lmat.multiplyToRef(parentScaleInv, lmat);
  68768. }
  68769. else {
  68770. lmat.multiplyToRef(rmat, lmat);
  68771. }
  68772. }
  68773. lmat.m[12] = lx;
  68774. lmat.m[13] = ly;
  68775. lmat.m[14] = lz;
  68776. this.computeAbsoluteTransforms();
  68777. this.markAsDirty();
  68778. };
  68779. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68781. if (space == BABYLON.Space.WORLD) {
  68782. var scaleMatrix = Bone._tmpMats[2];
  68783. scaleMatrix.copyFrom(this._scaleMatrix);
  68784. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68785. if (mesh) {
  68786. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68787. var meshScale = Bone._tmpMats[3];
  68788. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68789. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68790. }
  68791. rotMatInv.invert();
  68792. scaleMatrix.m[0] *= this._scalingDeterminant;
  68793. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68794. }
  68795. else {
  68796. rotMatInv.copyFrom(this.getLocalMatrix());
  68797. rotMatInv.invert();
  68798. var scaleMatrix = Bone._tmpMats[2];
  68799. scaleMatrix.copyFrom(this._scaleMatrix);
  68800. if (this._parent) {
  68801. var pscaleMatrix = Bone._tmpMats[3];
  68802. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68803. pscaleMatrix.invert();
  68804. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68805. }
  68806. else {
  68807. scaleMatrix.m[0] *= this._scalingDeterminant;
  68808. }
  68809. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68810. }
  68811. };
  68812. /**
  68813. * Get the scale of the bone
  68814. * @returns the scale of the bone
  68815. */
  68816. Bone.prototype.getScale = function () {
  68817. return this._scaleVector.clone();
  68818. };
  68819. /**
  68820. * Copy the scale of the bone to a vector3.
  68821. * @param result The vector3 to copy the scale to
  68822. */
  68823. Bone.prototype.getScaleToRef = function (result) {
  68824. result.copyFrom(this._scaleVector);
  68825. };
  68826. /**
  68827. * Get the position of the bone in local or world space.
  68828. * @param space The space that the returned position is in.
  68829. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68830. * @returns The position of the bone
  68831. */
  68832. Bone.prototype.getPosition = function (space, mesh) {
  68833. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68834. if (mesh === void 0) { mesh = null; }
  68835. var pos = BABYLON.Vector3.Zero();
  68836. this.getPositionToRef(space, mesh, pos);
  68837. return pos;
  68838. };
  68839. /**
  68840. * Copy the position of the bone to a vector3 in local or world space.
  68841. * @param space The space that the returned position is in.
  68842. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68843. * @param result The vector3 to copy the position to.
  68844. */
  68845. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68847. if (space == BABYLON.Space.LOCAL) {
  68848. var lm = this.getLocalMatrix();
  68849. result.x = lm.m[12];
  68850. result.y = lm.m[13];
  68851. result.z = lm.m[14];
  68852. }
  68853. else {
  68854. var wm = null;
  68855. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68856. if (mesh) {
  68857. wm = mesh.getWorldMatrix();
  68858. }
  68859. this._skeleton.computeAbsoluteTransforms();
  68860. var tmat = Bone._tmpMats[0];
  68861. if (mesh && wm) {
  68862. tmat.copyFrom(this.getAbsoluteTransform());
  68863. tmat.multiplyToRef(wm, tmat);
  68864. }
  68865. else {
  68866. tmat = this.getAbsoluteTransform();
  68867. }
  68868. result.x = tmat.m[12];
  68869. result.y = tmat.m[13];
  68870. result.z = tmat.m[14];
  68871. }
  68872. };
  68873. /**
  68874. * Get the absolute position of the bone (world space).
  68875. * @param mesh The mesh that this bone is attached to.
  68876. * @returns The absolute position of the bone
  68877. */
  68878. Bone.prototype.getAbsolutePosition = function (mesh) {
  68879. if (mesh === void 0) { mesh = null; }
  68880. var pos = BABYLON.Vector3.Zero();
  68881. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  68882. return pos;
  68883. };
  68884. /**
  68885. * Copy the absolute position of the bone (world space) to the result param.
  68886. * @param mesh The mesh that this bone is attached to.
  68887. * @param result The vector3 to copy the absolute position to.
  68888. */
  68889. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  68890. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  68891. };
  68892. /**
  68893. * Compute the absolute transforms of this bone and its children.
  68894. */
  68895. Bone.prototype.computeAbsoluteTransforms = function () {
  68896. if (this._parent) {
  68897. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68898. }
  68899. else {
  68900. this._absoluteTransform.copyFrom(this._localMatrix);
  68901. var poseMatrix = this._skeleton.getPoseMatrix();
  68902. if (poseMatrix) {
  68903. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  68904. }
  68905. }
  68906. var children = this.children;
  68907. var len = children.length;
  68908. for (var i = 0; i < len; i++) {
  68909. children[i].computeAbsoluteTransforms();
  68910. }
  68911. };
  68912. Bone.prototype._syncScaleVector = function () {
  68913. var lm = this.getLocalMatrix();
  68914. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  68915. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  68916. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  68917. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  68918. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  68919. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  68920. this._scaleVector.x = xs * Math.sqrt(xsq);
  68921. this._scaleVector.y = ys * Math.sqrt(ysq);
  68922. this._scaleVector.z = zs * Math.sqrt(zsq);
  68923. if (this._parent) {
  68924. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  68925. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  68926. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  68927. }
  68928. 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);
  68929. };
  68930. /**
  68931. * Get the world direction from an axis that is in the local space of the bone.
  68932. * @param localAxis The local direction that is used to compute the world direction.
  68933. * @param mesh The mesh that this bone is attached to.
  68934. * @returns The world direction
  68935. */
  68936. Bone.prototype.getDirection = function (localAxis, mesh) {
  68937. if (mesh === void 0) { mesh = null; }
  68938. var result = BABYLON.Vector3.Zero();
  68939. this.getDirectionToRef(localAxis, mesh, result);
  68940. return result;
  68941. };
  68942. /**
  68943. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  68944. * @param localAxis The local direction that is used to compute the world direction.
  68945. * @param mesh The mesh that this bone is attached to.
  68946. * @param result The vector3 that the world direction will be copied to.
  68947. */
  68948. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  68949. if (mesh === void 0) { mesh = null; }
  68950. var wm = null;
  68951. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68952. if (mesh) {
  68953. wm = mesh.getWorldMatrix();
  68954. }
  68955. this._skeleton.computeAbsoluteTransforms();
  68956. var mat = Bone._tmpMats[0];
  68957. mat.copyFrom(this.getAbsoluteTransform());
  68958. if (mesh && wm) {
  68959. mat.multiplyToRef(wm, mat);
  68960. }
  68961. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  68962. result.normalize();
  68963. };
  68964. /**
  68965. * Get the euler rotation of the bone in local or world space.
  68966. * @param space The space that the rotation should be in.
  68967. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68968. * @returns The euler rotation
  68969. */
  68970. Bone.prototype.getRotation = function (space, mesh) {
  68971. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68972. if (mesh === void 0) { mesh = null; }
  68973. var result = BABYLON.Vector3.Zero();
  68974. this.getRotationToRef(space, mesh, result);
  68975. return result;
  68976. };
  68977. /**
  68978. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  68979. * @param space The space that the rotation should be in.
  68980. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68981. * @param result The vector3 that the rotation should be copied to.
  68982. */
  68983. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  68984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68985. if (mesh === void 0) { mesh = null; }
  68986. var quat = Bone._tmpQuat;
  68987. this.getRotationQuaternionToRef(space, mesh, quat);
  68988. quat.toEulerAnglesToRef(result);
  68989. };
  68990. /**
  68991. * Get the quaternion rotation of the bone in either local or world space.
  68992. * @param space The space that the rotation should be in.
  68993. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68994. * @returns The quaternion rotation
  68995. */
  68996. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  68997. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68998. if (mesh === void 0) { mesh = null; }
  68999. var result = BABYLON.Quaternion.Identity();
  69000. this.getRotationQuaternionToRef(space, mesh, result);
  69001. return result;
  69002. };
  69003. /**
  69004. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69005. * @param space The space that the rotation should be in.
  69006. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69007. * @param result The quaternion that the rotation should be copied to.
  69008. */
  69009. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69010. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69011. if (mesh === void 0) { mesh = null; }
  69012. if (space == BABYLON.Space.LOCAL) {
  69013. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69014. }
  69015. else {
  69016. var mat = Bone._tmpMats[0];
  69017. var amat = this.getAbsoluteTransform();
  69018. if (mesh) {
  69019. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69020. }
  69021. else {
  69022. mat.copyFrom(amat);
  69023. }
  69024. mat.m[0] *= this._scalingDeterminant;
  69025. mat.m[1] *= this._scalingDeterminant;
  69026. mat.m[2] *= this._scalingDeterminant;
  69027. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69028. }
  69029. };
  69030. /**
  69031. * Get the rotation matrix of the bone in local or world space.
  69032. * @param space The space that the rotation should be in.
  69033. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69034. * @returns The rotation matrix
  69035. */
  69036. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69038. var result = BABYLON.Matrix.Identity();
  69039. this.getRotationMatrixToRef(space, mesh, result);
  69040. return result;
  69041. };
  69042. /**
  69043. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69044. * @param space The space that the rotation should be in.
  69045. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69046. * @param result The quaternion that the rotation should be copied to.
  69047. */
  69048. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69050. if (space == BABYLON.Space.LOCAL) {
  69051. this.getLocalMatrix().getRotationMatrixToRef(result);
  69052. }
  69053. else {
  69054. var mat = Bone._tmpMats[0];
  69055. var amat = this.getAbsoluteTransform();
  69056. if (mesh) {
  69057. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69058. }
  69059. else {
  69060. mat.copyFrom(amat);
  69061. }
  69062. mat.m[0] *= this._scalingDeterminant;
  69063. mat.m[1] *= this._scalingDeterminant;
  69064. mat.m[2] *= this._scalingDeterminant;
  69065. mat.getRotationMatrixToRef(result);
  69066. }
  69067. };
  69068. /**
  69069. * Get the world position of a point that is in the local space of the bone.
  69070. * @param position The local position
  69071. * @param mesh The mesh that this bone is attached to.
  69072. * @returns The world position
  69073. */
  69074. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69075. if (mesh === void 0) { mesh = null; }
  69076. var result = BABYLON.Vector3.Zero();
  69077. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69078. return result;
  69079. };
  69080. /**
  69081. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69082. * @param position The local position
  69083. * @param mesh The mesh that this bone is attached to.
  69084. * @param result The vector3 that the world position should be copied to.
  69085. */
  69086. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69087. if (mesh === void 0) { mesh = null; }
  69088. var wm = null;
  69089. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69090. if (mesh) {
  69091. wm = mesh.getWorldMatrix();
  69092. }
  69093. this._skeleton.computeAbsoluteTransforms();
  69094. var tmat = Bone._tmpMats[0];
  69095. if (mesh && wm) {
  69096. tmat.copyFrom(this.getAbsoluteTransform());
  69097. tmat.multiplyToRef(wm, tmat);
  69098. }
  69099. else {
  69100. tmat = this.getAbsoluteTransform();
  69101. }
  69102. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69103. };
  69104. /**
  69105. * Get the local position of a point that is in world space.
  69106. * @param position The world position
  69107. * @param mesh The mesh that this bone is attached to.
  69108. * @returns The local position
  69109. */
  69110. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69111. if (mesh === void 0) { mesh = null; }
  69112. var result = BABYLON.Vector3.Zero();
  69113. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69114. return result;
  69115. };
  69116. /**
  69117. * Get the local position of a point that is in world space and copy it to the result param.
  69118. * @param position The world position
  69119. * @param mesh The mesh that this bone is attached to.
  69120. * @param result The vector3 that the local position should be copied to.
  69121. */
  69122. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69123. if (mesh === void 0) { mesh = null; }
  69124. var wm = null;
  69125. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69126. if (mesh) {
  69127. wm = mesh.getWorldMatrix();
  69128. }
  69129. this._skeleton.computeAbsoluteTransforms();
  69130. var tmat = Bone._tmpMats[0];
  69131. tmat.copyFrom(this.getAbsoluteTransform());
  69132. if (mesh && wm) {
  69133. tmat.multiplyToRef(wm, tmat);
  69134. }
  69135. tmat.invert();
  69136. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69137. };
  69138. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69139. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69140. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69141. return Bone;
  69142. }(BABYLON.Node));
  69143. BABYLON.Bone = Bone;
  69144. })(BABYLON || (BABYLON = {}));
  69145. //# sourceMappingURL=babylon.bone.js.map
  69146. var BABYLON;
  69147. (function (BABYLON) {
  69148. var BoneIKController = /** @class */ (function () {
  69149. function BoneIKController(mesh, bone, options) {
  69150. this.targetPosition = BABYLON.Vector3.Zero();
  69151. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69152. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69153. this.poleAngle = 0;
  69154. this.slerpAmount = 1;
  69155. this._bone1Quat = BABYLON.Quaternion.Identity();
  69156. this._bone1Mat = BABYLON.Matrix.Identity();
  69157. this._bone2Ang = Math.PI;
  69158. this._maxAngle = Math.PI;
  69159. this._rightHandedSystem = false;
  69160. this._bendAxis = BABYLON.Vector3.Right();
  69161. this._slerping = false;
  69162. this._adjustRoll = 0;
  69163. this._bone2 = bone;
  69164. this._bone1 = bone.getParent();
  69165. if (!this._bone1) {
  69166. return;
  69167. }
  69168. this.mesh = mesh;
  69169. var bonePos = bone.getPosition();
  69170. if (bone.getAbsoluteTransform().determinant() > 0) {
  69171. this._rightHandedSystem = true;
  69172. this._bendAxis.x = 0;
  69173. this._bendAxis.y = 0;
  69174. this._bendAxis.z = -1;
  69175. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69176. this._adjustRoll = Math.PI * .5;
  69177. this._bendAxis.z = 1;
  69178. }
  69179. }
  69180. if (this._bone1.length) {
  69181. var boneScale1 = this._bone1.getScale();
  69182. var boneScale2 = this._bone2.getScale();
  69183. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69184. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69185. }
  69186. else if (this._bone1.children[0]) {
  69187. mesh.computeWorldMatrix(true);
  69188. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69189. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69190. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69191. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69192. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69193. }
  69194. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69195. this.maxAngle = Math.PI;
  69196. if (options) {
  69197. if (options.targetMesh) {
  69198. this.targetMesh = options.targetMesh;
  69199. this.targetMesh.computeWorldMatrix(true);
  69200. }
  69201. if (options.poleTargetMesh) {
  69202. this.poleTargetMesh = options.poleTargetMesh;
  69203. this.poleTargetMesh.computeWorldMatrix(true);
  69204. }
  69205. else if (options.poleTargetBone) {
  69206. this.poleTargetBone = options.poleTargetBone;
  69207. }
  69208. else if (this._bone1.getParent()) {
  69209. this.poleTargetBone = this._bone1.getParent();
  69210. }
  69211. if (options.poleTargetLocalOffset) {
  69212. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69213. }
  69214. if (options.poleAngle) {
  69215. this.poleAngle = options.poleAngle;
  69216. }
  69217. if (options.bendAxis) {
  69218. this._bendAxis.copyFrom(options.bendAxis);
  69219. }
  69220. if (options.maxAngle) {
  69221. this.maxAngle = options.maxAngle;
  69222. }
  69223. if (options.slerpAmount) {
  69224. this.slerpAmount = options.slerpAmount;
  69225. }
  69226. }
  69227. }
  69228. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69229. get: function () {
  69230. return this._maxAngle;
  69231. },
  69232. set: function (value) {
  69233. this._setMaxAngle(value);
  69234. },
  69235. enumerable: true,
  69236. configurable: true
  69237. });
  69238. BoneIKController.prototype._setMaxAngle = function (ang) {
  69239. if (ang < 0) {
  69240. ang = 0;
  69241. }
  69242. if (ang > Math.PI || ang == undefined) {
  69243. ang = Math.PI;
  69244. }
  69245. this._maxAngle = ang;
  69246. var a = this._bone1Length;
  69247. var b = this._bone2Length;
  69248. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69249. };
  69250. BoneIKController.prototype.update = function () {
  69251. var bone1 = this._bone1;
  69252. if (!bone1) {
  69253. return;
  69254. }
  69255. var target = this.targetPosition;
  69256. var poleTarget = this.poleTargetPosition;
  69257. var mat1 = BoneIKController._tmpMats[0];
  69258. var mat2 = BoneIKController._tmpMats[1];
  69259. if (this.targetMesh) {
  69260. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69261. }
  69262. if (this.poleTargetBone) {
  69263. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69264. }
  69265. else if (this.poleTargetMesh) {
  69266. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69267. }
  69268. var bonePos = BoneIKController._tmpVecs[0];
  69269. var zaxis = BoneIKController._tmpVecs[1];
  69270. var xaxis = BoneIKController._tmpVecs[2];
  69271. var yaxis = BoneIKController._tmpVecs[3];
  69272. var upAxis = BoneIKController._tmpVecs[4];
  69273. var _tmpQuat = BoneIKController._tmpQuat;
  69274. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69275. poleTarget.subtractToRef(bonePos, upAxis);
  69276. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69277. upAxis.y = 1;
  69278. }
  69279. else {
  69280. upAxis.normalize();
  69281. }
  69282. target.subtractToRef(bonePos, yaxis);
  69283. yaxis.normalize();
  69284. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69285. zaxis.normalize();
  69286. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69287. xaxis.normalize();
  69288. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69289. var a = this._bone1Length;
  69290. var b = this._bone2Length;
  69291. var c = BABYLON.Vector3.Distance(bonePos, target);
  69292. if (this._maxReach > 0) {
  69293. c = Math.min(this._maxReach, c);
  69294. }
  69295. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69296. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69297. if (acosa > 1) {
  69298. acosa = 1;
  69299. }
  69300. if (acosb > 1) {
  69301. acosb = 1;
  69302. }
  69303. if (acosa < -1) {
  69304. acosa = -1;
  69305. }
  69306. if (acosb < -1) {
  69307. acosb = -1;
  69308. }
  69309. var angA = Math.acos(acosa);
  69310. var angB = Math.acos(acosb);
  69311. var angC = -angA - angB;
  69312. if (this._rightHandedSystem) {
  69313. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69314. mat2.multiplyToRef(mat1, mat1);
  69315. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69316. mat2.multiplyToRef(mat1, mat1);
  69317. }
  69318. else {
  69319. var _tmpVec = BoneIKController._tmpVecs[5];
  69320. _tmpVec.copyFrom(this._bendAxis);
  69321. _tmpVec.x *= -1;
  69322. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69323. mat2.multiplyToRef(mat1, mat1);
  69324. }
  69325. if (this.poleAngle) {
  69326. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69327. mat1.multiplyToRef(mat2, mat1);
  69328. }
  69329. if (this._bone1) {
  69330. if (this.slerpAmount < 1) {
  69331. if (!this._slerping) {
  69332. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69333. }
  69334. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69335. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69336. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69337. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69338. this._slerping = true;
  69339. }
  69340. else {
  69341. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69342. this._bone1Mat.copyFrom(mat1);
  69343. this._slerping = false;
  69344. }
  69345. }
  69346. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69347. this._bone2Ang = angC;
  69348. };
  69349. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69350. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69351. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69352. return BoneIKController;
  69353. }());
  69354. BABYLON.BoneIKController = BoneIKController;
  69355. })(BABYLON || (BABYLON = {}));
  69356. //# sourceMappingURL=babylon.boneIKController.js.map
  69357. var BABYLON;
  69358. (function (BABYLON) {
  69359. var BoneLookController = /** @class */ (function () {
  69360. /**
  69361. * Create a BoneLookController
  69362. * @param mesh the mesh that the bone belongs to
  69363. * @param bone the bone that will be looking to the target
  69364. * @param target the target Vector3 to look at
  69365. * @param settings optional settings:
  69366. * - maxYaw: the maximum angle the bone will yaw to
  69367. * - minYaw: the minimum angle the bone will yaw to
  69368. * - maxPitch: the maximum angle the bone will pitch to
  69369. * - minPitch: the minimum angle the bone will yaw to
  69370. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69371. * - upAxis: the up axis of the coordinate system
  69372. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69373. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69374. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69375. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69376. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69377. * - adjustRoll: used to make an adjustment to the roll of the bone
  69378. **/
  69379. function BoneLookController(mesh, bone, target, options) {
  69380. /**
  69381. * The up axis of the coordinate system that is used when the bone is rotated.
  69382. */
  69383. this.upAxis = BABYLON.Vector3.Up();
  69384. /**
  69385. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69386. */
  69387. this.upAxisSpace = BABYLON.Space.LOCAL;
  69388. /**
  69389. * Used to make an adjustment to the yaw of the bone.
  69390. */
  69391. this.adjustYaw = 0;
  69392. /**
  69393. * Used to make an adjustment to the pitch of the bone.
  69394. */
  69395. this.adjustPitch = 0;
  69396. /**
  69397. * Used to make an adjustment to the roll of the bone.
  69398. */
  69399. this.adjustRoll = 0;
  69400. /**
  69401. * 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).
  69402. */
  69403. this.slerpAmount = 1;
  69404. this._boneQuat = BABYLON.Quaternion.Identity();
  69405. this._slerping = false;
  69406. this._firstFrameSkipped = false;
  69407. this._fowardAxis = BABYLON.Vector3.Forward();
  69408. this.mesh = mesh;
  69409. this.bone = bone;
  69410. this.target = target;
  69411. if (options) {
  69412. if (options.adjustYaw) {
  69413. this.adjustYaw = options.adjustYaw;
  69414. }
  69415. if (options.adjustPitch) {
  69416. this.adjustPitch = options.adjustPitch;
  69417. }
  69418. if (options.adjustRoll) {
  69419. this.adjustRoll = options.adjustRoll;
  69420. }
  69421. if (options.maxYaw != null) {
  69422. this.maxYaw = options.maxYaw;
  69423. }
  69424. else {
  69425. this.maxYaw = Math.PI;
  69426. }
  69427. if (options.minYaw != null) {
  69428. this.minYaw = options.minYaw;
  69429. }
  69430. else {
  69431. this.minYaw = -Math.PI;
  69432. }
  69433. if (options.maxPitch != null) {
  69434. this.maxPitch = options.maxPitch;
  69435. }
  69436. else {
  69437. this.maxPitch = Math.PI;
  69438. }
  69439. if (options.minPitch != null) {
  69440. this.minPitch = options.minPitch;
  69441. }
  69442. else {
  69443. this.minPitch = -Math.PI;
  69444. }
  69445. if (options.slerpAmount != null) {
  69446. this.slerpAmount = options.slerpAmount;
  69447. }
  69448. if (options.upAxis != null) {
  69449. this.upAxis = options.upAxis;
  69450. }
  69451. if (options.upAxisSpace != null) {
  69452. this.upAxisSpace = options.upAxisSpace;
  69453. }
  69454. if (options.yawAxis != null || options.pitchAxis != null) {
  69455. var newYawAxis = BABYLON.Axis.Y;
  69456. var newPitchAxis = BABYLON.Axis.X;
  69457. if (options.yawAxis != null) {
  69458. newYawAxis = options.yawAxis.clone();
  69459. newYawAxis.normalize();
  69460. }
  69461. if (options.pitchAxis != null) {
  69462. newPitchAxis = options.pitchAxis.clone();
  69463. newPitchAxis.normalize();
  69464. }
  69465. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69466. this._transformYawPitch = BABYLON.Matrix.Identity();
  69467. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69468. this._transformYawPitchInv = this._transformYawPitch.clone();
  69469. this._transformYawPitch.invert();
  69470. }
  69471. }
  69472. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69473. this.upAxisSpace = BABYLON.Space.LOCAL;
  69474. }
  69475. }
  69476. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69477. /**
  69478. * Get/set the minimum yaw angle that the bone can look to.
  69479. */
  69480. get: function () {
  69481. return this._minYaw;
  69482. },
  69483. set: function (value) {
  69484. this._minYaw = value;
  69485. this._minYawSin = Math.sin(value);
  69486. this._minYawCos = Math.cos(value);
  69487. if (this._maxYaw != null) {
  69488. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69489. this._yawRange = this._maxYaw - this._minYaw;
  69490. }
  69491. },
  69492. enumerable: true,
  69493. configurable: true
  69494. });
  69495. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69496. /**
  69497. * Get/set the maximum yaw angle that the bone can look to.
  69498. */
  69499. get: function () {
  69500. return this._maxYaw;
  69501. },
  69502. set: function (value) {
  69503. this._maxYaw = value;
  69504. this._maxYawSin = Math.sin(value);
  69505. this._maxYawCos = Math.cos(value);
  69506. if (this._minYaw != null) {
  69507. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69508. this._yawRange = this._maxYaw - this._minYaw;
  69509. }
  69510. },
  69511. enumerable: true,
  69512. configurable: true
  69513. });
  69514. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69515. /**
  69516. * Get/set the minimum pitch angle that the bone can look to.
  69517. */
  69518. get: function () {
  69519. return this._minPitch;
  69520. },
  69521. set: function (value) {
  69522. this._minPitch = value;
  69523. this._minPitchTan = Math.tan(value);
  69524. },
  69525. enumerable: true,
  69526. configurable: true
  69527. });
  69528. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69529. /**
  69530. * Get/set the maximum pitch angle that the bone can look to.
  69531. */
  69532. get: function () {
  69533. return this._maxPitch;
  69534. },
  69535. set: function (value) {
  69536. this._maxPitch = value;
  69537. this._maxPitchTan = Math.tan(value);
  69538. },
  69539. enumerable: true,
  69540. configurable: true
  69541. });
  69542. /**
  69543. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69544. */
  69545. BoneLookController.prototype.update = function () {
  69546. //skip the first frame when slerping so that the mesh rotation is correct
  69547. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69548. this._firstFrameSkipped = true;
  69549. return;
  69550. }
  69551. var bone = this.bone;
  69552. var bonePos = BoneLookController._tmpVecs[0];
  69553. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69554. var target = this.target;
  69555. var _tmpMat1 = BoneLookController._tmpMats[0];
  69556. var _tmpMat2 = BoneLookController._tmpMats[1];
  69557. var mesh = this.mesh;
  69558. var parentBone = bone.getParent();
  69559. var upAxis = BoneLookController._tmpVecs[1];
  69560. upAxis.copyFrom(this.upAxis);
  69561. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69562. if (this._transformYawPitch) {
  69563. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69564. }
  69565. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69566. }
  69567. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69568. mesh.getDirectionToRef(upAxis, upAxis);
  69569. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69570. upAxis.normalize();
  69571. }
  69572. }
  69573. var checkYaw = false;
  69574. var checkPitch = false;
  69575. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69576. checkYaw = true;
  69577. }
  69578. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69579. checkPitch = true;
  69580. }
  69581. if (checkYaw || checkPitch) {
  69582. var spaceMat = BoneLookController._tmpMats[2];
  69583. var spaceMatInv = BoneLookController._tmpMats[3];
  69584. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69585. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69586. }
  69587. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69588. spaceMat.copyFrom(mesh.getWorldMatrix());
  69589. }
  69590. else {
  69591. var forwardAxis = BoneLookController._tmpVecs[2];
  69592. forwardAxis.copyFrom(this._fowardAxis);
  69593. if (this._transformYawPitch) {
  69594. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69595. }
  69596. if (parentBone) {
  69597. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69598. }
  69599. else {
  69600. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69601. }
  69602. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69603. rightAxis.normalize();
  69604. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69605. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69606. }
  69607. spaceMat.invertToRef(spaceMatInv);
  69608. var xzlen = null;
  69609. if (checkPitch) {
  69610. var localTarget = BoneLookController._tmpVecs[3];
  69611. target.subtractToRef(bonePos, localTarget);
  69612. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69613. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69614. var pitch = Math.atan2(localTarget.y, xzlen);
  69615. var newPitch = pitch;
  69616. if (pitch > this._maxPitch) {
  69617. localTarget.y = this._maxPitchTan * xzlen;
  69618. newPitch = this._maxPitch;
  69619. }
  69620. else if (pitch < this._minPitch) {
  69621. localTarget.y = this._minPitchTan * xzlen;
  69622. newPitch = this._minPitch;
  69623. }
  69624. if (pitch != newPitch) {
  69625. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69626. localTarget.addInPlace(bonePos);
  69627. target = localTarget;
  69628. }
  69629. }
  69630. if (checkYaw) {
  69631. var localTarget = BoneLookController._tmpVecs[4];
  69632. target.subtractToRef(bonePos, localTarget);
  69633. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69634. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69635. var newYaw = yaw;
  69636. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69637. if (xzlen == null) {
  69638. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69639. }
  69640. if (this._yawRange > Math.PI) {
  69641. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69642. localTarget.z = this._maxYawCos * xzlen;
  69643. localTarget.x = this._maxYawSin * xzlen;
  69644. newYaw = this._maxYaw;
  69645. }
  69646. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69647. localTarget.z = this._minYawCos * xzlen;
  69648. localTarget.x = this._minYawSin * xzlen;
  69649. newYaw = this._minYaw;
  69650. }
  69651. }
  69652. else {
  69653. if (yaw > this._maxYaw) {
  69654. localTarget.z = this._maxYawCos * xzlen;
  69655. localTarget.x = this._maxYawSin * xzlen;
  69656. newYaw = this._maxYaw;
  69657. }
  69658. else if (yaw < this._minYaw) {
  69659. localTarget.z = this._minYawCos * xzlen;
  69660. localTarget.x = this._minYawSin * xzlen;
  69661. newYaw = this._minYaw;
  69662. }
  69663. }
  69664. }
  69665. if (this._slerping && this._yawRange > Math.PI) {
  69666. //are we going to be crossing into the min/max region?
  69667. var boneFwd = BoneLookController._tmpVecs[8];
  69668. boneFwd.copyFrom(BABYLON.Axis.Z);
  69669. if (this._transformYawPitch) {
  69670. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69671. }
  69672. var boneRotMat = BoneLookController._tmpMats[4];
  69673. this._boneQuat.toRotationMatrix(boneRotMat);
  69674. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69675. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69676. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69677. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69678. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69679. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69680. if (angBtwTar > angBtwMidYaw) {
  69681. if (xzlen == null) {
  69682. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69683. }
  69684. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69685. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69686. if (angBtwMin < angBtwMax) {
  69687. newYaw = boneYaw + Math.PI * .75;
  69688. localTarget.z = Math.cos(newYaw) * xzlen;
  69689. localTarget.x = Math.sin(newYaw) * xzlen;
  69690. }
  69691. else {
  69692. newYaw = boneYaw - Math.PI * .75;
  69693. localTarget.z = Math.cos(newYaw) * xzlen;
  69694. localTarget.x = Math.sin(newYaw) * xzlen;
  69695. }
  69696. }
  69697. }
  69698. if (yaw != newYaw) {
  69699. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69700. localTarget.addInPlace(bonePos);
  69701. target = localTarget;
  69702. }
  69703. }
  69704. }
  69705. var zaxis = BoneLookController._tmpVecs[5];
  69706. var xaxis = BoneLookController._tmpVecs[6];
  69707. var yaxis = BoneLookController._tmpVecs[7];
  69708. var _tmpQuat = BoneLookController._tmpQuat;
  69709. target.subtractToRef(bonePos, zaxis);
  69710. zaxis.normalize();
  69711. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69712. xaxis.normalize();
  69713. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69714. yaxis.normalize();
  69715. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69716. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69717. return;
  69718. }
  69719. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69720. return;
  69721. }
  69722. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69723. return;
  69724. }
  69725. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69726. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69727. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69728. }
  69729. if (this.slerpAmount < 1) {
  69730. if (!this._slerping) {
  69731. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69732. }
  69733. if (this._transformYawPitch) {
  69734. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69735. }
  69736. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69737. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69738. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69739. this._slerping = true;
  69740. }
  69741. else {
  69742. if (this._transformYawPitch) {
  69743. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69744. }
  69745. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69746. this._slerping = false;
  69747. }
  69748. };
  69749. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69750. var angDiff = ang2 - ang1;
  69751. angDiff %= Math.PI * 2;
  69752. if (angDiff > Math.PI) {
  69753. angDiff -= Math.PI * 2;
  69754. }
  69755. else if (angDiff < -Math.PI) {
  69756. angDiff += Math.PI * 2;
  69757. }
  69758. return angDiff;
  69759. };
  69760. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69761. ang1 %= (2 * Math.PI);
  69762. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69763. ang2 %= (2 * Math.PI);
  69764. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69765. var ab = 0;
  69766. if (ang1 < ang2) {
  69767. ab = ang2 - ang1;
  69768. }
  69769. else {
  69770. ab = ang1 - ang2;
  69771. }
  69772. if (ab > Math.PI) {
  69773. ab = Math.PI * 2 - ab;
  69774. }
  69775. return ab;
  69776. };
  69777. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69778. ang %= (2 * Math.PI);
  69779. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69780. ang1 %= (2 * Math.PI);
  69781. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69782. ang2 %= (2 * Math.PI);
  69783. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69784. if (ang1 < ang2) {
  69785. if (ang > ang1 && ang < ang2) {
  69786. return true;
  69787. }
  69788. }
  69789. else {
  69790. if (ang > ang2 && ang < ang1) {
  69791. return true;
  69792. }
  69793. }
  69794. return false;
  69795. };
  69796. 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()];
  69797. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69798. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69799. return BoneLookController;
  69800. }());
  69801. BABYLON.BoneLookController = BoneLookController;
  69802. })(BABYLON || (BABYLON = {}));
  69803. //# sourceMappingURL=babylon.boneLookController.js.map
  69804. var BABYLON;
  69805. (function (BABYLON) {
  69806. var Skeleton = /** @class */ (function () {
  69807. function Skeleton(name, id, scene) {
  69808. this.name = name;
  69809. this.id = id;
  69810. this.bones = new Array();
  69811. this.needInitialSkinMatrix = false;
  69812. this._isDirty = true;
  69813. this._meshesWithPoseMatrix = new Array();
  69814. this._identity = BABYLON.Matrix.Identity();
  69815. this._ranges = {};
  69816. this._lastAbsoluteTransformsUpdateId = -1;
  69817. // Events
  69818. /**
  69819. * An event triggered before computing the skeleton's matrices
  69820. * @type {BABYLON.Observable}
  69821. */
  69822. this.onBeforeComputeObservable = new BABYLON.Observable();
  69823. this.bones = [];
  69824. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69825. scene.skeletons.push(this);
  69826. //make sure it will recalculate the matrix next time prepare is called.
  69827. this._isDirty = true;
  69828. }
  69829. // Members
  69830. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69831. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69832. return mesh._bonesTransformMatrices;
  69833. }
  69834. if (!this._transformMatrices) {
  69835. this.prepare();
  69836. }
  69837. return this._transformMatrices;
  69838. };
  69839. Skeleton.prototype.getScene = function () {
  69840. return this._scene;
  69841. };
  69842. // Methods
  69843. /**
  69844. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69845. */
  69846. Skeleton.prototype.toString = function (fullDetails) {
  69847. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69848. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69849. if (fullDetails) {
  69850. ret += ", Ranges: {";
  69851. var first = true;
  69852. for (var name_1 in this._ranges) {
  69853. if (first) {
  69854. ret += ", ";
  69855. first = false;
  69856. }
  69857. ret += name_1;
  69858. }
  69859. ret += "}";
  69860. }
  69861. return ret;
  69862. };
  69863. /**
  69864. * Get bone's index searching by name
  69865. * @param {string} name is bone's name to search for
  69866. * @return {number} Indice of the bone. Returns -1 if not found
  69867. */
  69868. Skeleton.prototype.getBoneIndexByName = function (name) {
  69869. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69870. if (this.bones[boneIndex].name === name) {
  69871. return boneIndex;
  69872. }
  69873. }
  69874. return -1;
  69875. };
  69876. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  69877. // check name not already in use
  69878. if (!this._ranges[name]) {
  69879. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  69880. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69881. if (this.bones[i].animations[0]) {
  69882. this.bones[i].animations[0].createRange(name, from, to);
  69883. }
  69884. }
  69885. }
  69886. };
  69887. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  69888. if (deleteFrames === void 0) { deleteFrames = true; }
  69889. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69890. if (this.bones[i].animations[0]) {
  69891. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  69892. }
  69893. }
  69894. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  69895. };
  69896. Skeleton.prototype.getAnimationRange = function (name) {
  69897. return this._ranges[name];
  69898. };
  69899. /**
  69900. * Returns as an Array, all AnimationRanges defined on this skeleton
  69901. */
  69902. Skeleton.prototype.getAnimationRanges = function () {
  69903. var animationRanges = [];
  69904. var name;
  69905. var i = 0;
  69906. for (name in this._ranges) {
  69907. animationRanges[i] = this._ranges[name];
  69908. i++;
  69909. }
  69910. return animationRanges;
  69911. };
  69912. /**
  69913. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  69914. */
  69915. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  69916. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69917. if (this._ranges[name] || !source.getAnimationRange(name)) {
  69918. return false;
  69919. }
  69920. var ret = true;
  69921. var frameOffset = this._getHighestAnimationFrame() + 1;
  69922. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  69923. var boneDict = {};
  69924. var sourceBones = source.bones;
  69925. var nBones;
  69926. var i;
  69927. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  69928. boneDict[sourceBones[i].name] = sourceBones[i];
  69929. }
  69930. if (this.bones.length !== sourceBones.length) {
  69931. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  69932. ret = false;
  69933. }
  69934. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  69935. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  69936. var boneName = this.bones[i].name;
  69937. var sourceBone = boneDict[boneName];
  69938. if (sourceBone) {
  69939. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  69940. }
  69941. else {
  69942. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  69943. ret = false;
  69944. }
  69945. }
  69946. // do not call createAnimationRange(), since it also is done to bones, which was already done
  69947. var range = source.getAnimationRange(name);
  69948. if (range) {
  69949. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  69950. }
  69951. return ret;
  69952. };
  69953. Skeleton.prototype.returnToRest = function () {
  69954. for (var index = 0; index < this.bones.length; index++) {
  69955. this.bones[index].returnToRest();
  69956. }
  69957. };
  69958. Skeleton.prototype._getHighestAnimationFrame = function () {
  69959. var ret = 0;
  69960. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69961. if (this.bones[i].animations[0]) {
  69962. var highest = this.bones[i].animations[0].getHighestFrame();
  69963. if (ret < highest) {
  69964. ret = highest;
  69965. }
  69966. }
  69967. }
  69968. return ret;
  69969. };
  69970. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  69971. var range = this.getAnimationRange(name);
  69972. if (!range) {
  69973. return null;
  69974. }
  69975. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  69976. };
  69977. Skeleton.prototype._markAsDirty = function () {
  69978. this._isDirty = true;
  69979. };
  69980. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  69981. this._meshesWithPoseMatrix.push(mesh);
  69982. };
  69983. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  69984. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  69985. if (index > -1) {
  69986. this._meshesWithPoseMatrix.splice(index, 1);
  69987. }
  69988. };
  69989. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  69990. this.onBeforeComputeObservable.notifyObservers(this);
  69991. for (var index = 0; index < this.bones.length; index++) {
  69992. var bone = this.bones[index];
  69993. var parentBone = bone.getParent();
  69994. if (parentBone) {
  69995. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  69996. }
  69997. else {
  69998. if (initialSkinMatrix) {
  69999. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70000. }
  70001. else {
  70002. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70003. }
  70004. }
  70005. if (bone._index !== -1) {
  70006. var mappedIndex = bone._index === null ? index : bone._index;
  70007. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70008. }
  70009. }
  70010. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70011. };
  70012. Skeleton.prototype.prepare = function () {
  70013. if (!this._isDirty) {
  70014. return;
  70015. }
  70016. if (this.needInitialSkinMatrix) {
  70017. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70018. var mesh = this._meshesWithPoseMatrix[index];
  70019. var poseMatrix = mesh.getPoseMatrix();
  70020. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70021. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70022. }
  70023. if (this._synchronizedWithMesh !== mesh) {
  70024. this._synchronizedWithMesh = mesh;
  70025. // Prepare bones
  70026. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70027. var bone = this.bones[boneIndex];
  70028. if (!bone.getParent()) {
  70029. var matrix = bone.getBaseMatrix();
  70030. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70031. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70032. }
  70033. }
  70034. }
  70035. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70036. }
  70037. }
  70038. else {
  70039. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70040. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70041. }
  70042. this._computeTransformMatrices(this._transformMatrices, null);
  70043. }
  70044. this._isDirty = false;
  70045. this._scene._activeBones.addCount(this.bones.length, false);
  70046. };
  70047. Skeleton.prototype.getAnimatables = function () {
  70048. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70049. this._animatables = [];
  70050. for (var index = 0; index < this.bones.length; index++) {
  70051. this._animatables.push(this.bones[index]);
  70052. }
  70053. }
  70054. return this._animatables;
  70055. };
  70056. Skeleton.prototype.clone = function (name, id) {
  70057. var result = new Skeleton(name, id || name, this._scene);
  70058. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70059. for (var index = 0; index < this.bones.length; index++) {
  70060. var source = this.bones[index];
  70061. var parentBone = null;
  70062. var parent_1 = source.getParent();
  70063. if (parent_1) {
  70064. var parentIndex = this.bones.indexOf(parent_1);
  70065. parentBone = result.bones[parentIndex];
  70066. }
  70067. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70068. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70069. }
  70070. if (this._ranges) {
  70071. result._ranges = {};
  70072. for (var rangeName in this._ranges) {
  70073. var range = this._ranges[rangeName];
  70074. if (range) {
  70075. result._ranges[rangeName] = range.clone();
  70076. }
  70077. }
  70078. }
  70079. this._isDirty = true;
  70080. return result;
  70081. };
  70082. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70083. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70084. this.bones.forEach(function (bone) {
  70085. bone.animations.forEach(function (animation) {
  70086. animation.enableBlending = true;
  70087. animation.blendingSpeed = blendingSpeed;
  70088. });
  70089. });
  70090. };
  70091. Skeleton.prototype.dispose = function () {
  70092. this._meshesWithPoseMatrix = [];
  70093. // Animations
  70094. this.getScene().stopAnimation(this);
  70095. // Remove from scene
  70096. this.getScene().removeSkeleton(this);
  70097. };
  70098. Skeleton.prototype.serialize = function () {
  70099. var serializationObject = {};
  70100. serializationObject.name = this.name;
  70101. serializationObject.id = this.id;
  70102. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70103. serializationObject.bones = [];
  70104. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70105. for (var index = 0; index < this.bones.length; index++) {
  70106. var bone = this.bones[index];
  70107. var parent_2 = bone.getParent();
  70108. var serializedBone = {
  70109. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70110. name: bone.name,
  70111. matrix: bone.getBaseMatrix().toArray(),
  70112. rest: bone.getRestPose().toArray()
  70113. };
  70114. serializationObject.bones.push(serializedBone);
  70115. if (bone.length) {
  70116. serializedBone.length = bone.length;
  70117. }
  70118. if (bone.animations && bone.animations.length > 0) {
  70119. serializedBone.animation = bone.animations[0].serialize();
  70120. }
  70121. serializationObject.ranges = [];
  70122. for (var name in this._ranges) {
  70123. var source = this._ranges[name];
  70124. if (!source) {
  70125. continue;
  70126. }
  70127. var range = {};
  70128. range.name = name;
  70129. range.from = source.from;
  70130. range.to = source.to;
  70131. serializationObject.ranges.push(range);
  70132. }
  70133. }
  70134. return serializationObject;
  70135. };
  70136. Skeleton.Parse = function (parsedSkeleton, scene) {
  70137. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70138. if (parsedSkeleton.dimensionsAtRest) {
  70139. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70140. }
  70141. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70142. var index;
  70143. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70144. var parsedBone = parsedSkeleton.bones[index];
  70145. var parentBone = null;
  70146. if (parsedBone.parentBoneIndex > -1) {
  70147. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70148. }
  70149. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70150. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70151. if (parsedBone.length) {
  70152. bone.length = parsedBone.length;
  70153. }
  70154. if (parsedBone.animation) {
  70155. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70156. }
  70157. }
  70158. // placed after bones, so createAnimationRange can cascade down
  70159. if (parsedSkeleton.ranges) {
  70160. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70161. var data = parsedSkeleton.ranges[index];
  70162. skeleton.createAnimationRange(data.name, data.from, data.to);
  70163. }
  70164. }
  70165. return skeleton;
  70166. };
  70167. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70168. if (forceUpdate === void 0) { forceUpdate = false; }
  70169. var renderId = this._scene.getRenderId();
  70170. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70171. this.bones[0].computeAbsoluteTransforms();
  70172. this._lastAbsoluteTransformsUpdateId = renderId;
  70173. }
  70174. };
  70175. Skeleton.prototype.getPoseMatrix = function () {
  70176. var poseMatrix = null;
  70177. if (this._meshesWithPoseMatrix.length > 0) {
  70178. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70179. }
  70180. return poseMatrix;
  70181. };
  70182. Skeleton.prototype.sortBones = function () {
  70183. var bones = new Array();
  70184. var visited = new Array(this.bones.length);
  70185. for (var index = 0; index < this.bones.length; index++) {
  70186. this._sortBones(index, bones, visited);
  70187. }
  70188. this.bones = bones;
  70189. };
  70190. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70191. if (visited[index]) {
  70192. return;
  70193. }
  70194. visited[index] = true;
  70195. var bone = this.bones[index];
  70196. if (bone._index === undefined) {
  70197. bone._index = index;
  70198. }
  70199. var parentBone = bone.getParent();
  70200. if (parentBone) {
  70201. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70202. }
  70203. bones.push(bone);
  70204. };
  70205. return Skeleton;
  70206. }());
  70207. BABYLON.Skeleton = Skeleton;
  70208. })(BABYLON || (BABYLON = {}));
  70209. //# sourceMappingURL=babylon.skeleton.js.map
  70210. var BABYLON;
  70211. (function (BABYLON) {
  70212. var SphericalPolynomial = /** @class */ (function () {
  70213. function SphericalPolynomial() {
  70214. this.x = BABYLON.Vector3.Zero();
  70215. this.y = BABYLON.Vector3.Zero();
  70216. this.z = BABYLON.Vector3.Zero();
  70217. this.xx = BABYLON.Vector3.Zero();
  70218. this.yy = BABYLON.Vector3.Zero();
  70219. this.zz = BABYLON.Vector3.Zero();
  70220. this.xy = BABYLON.Vector3.Zero();
  70221. this.yz = BABYLON.Vector3.Zero();
  70222. this.zx = BABYLON.Vector3.Zero();
  70223. }
  70224. SphericalPolynomial.prototype.addAmbient = function (color) {
  70225. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70226. this.xx = this.xx.add(colorVector);
  70227. this.yy = this.yy.add(colorVector);
  70228. this.zz = this.zz.add(colorVector);
  70229. };
  70230. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70231. var result = new SphericalPolynomial();
  70232. result.x = harmonics.L11.scale(1.02333);
  70233. result.y = harmonics.L1_1.scale(1.02333);
  70234. result.z = harmonics.L10.scale(1.02333);
  70235. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70236. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70237. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70238. result.yz = harmonics.L2_1.scale(0.858086);
  70239. result.zx = harmonics.L21.scale(0.858086);
  70240. result.xy = harmonics.L2_2.scale(0.858086);
  70241. result.scale(1.0 / Math.PI);
  70242. return result;
  70243. };
  70244. SphericalPolynomial.prototype.scale = function (scale) {
  70245. this.x = this.x.scale(scale);
  70246. this.y = this.y.scale(scale);
  70247. this.z = this.z.scale(scale);
  70248. this.xx = this.xx.scale(scale);
  70249. this.yy = this.yy.scale(scale);
  70250. this.zz = this.zz.scale(scale);
  70251. this.yz = this.yz.scale(scale);
  70252. this.zx = this.zx.scale(scale);
  70253. this.xy = this.xy.scale(scale);
  70254. };
  70255. return SphericalPolynomial;
  70256. }());
  70257. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70258. var SphericalHarmonics = /** @class */ (function () {
  70259. function SphericalHarmonics() {
  70260. this.L00 = BABYLON.Vector3.Zero();
  70261. this.L1_1 = BABYLON.Vector3.Zero();
  70262. this.L10 = BABYLON.Vector3.Zero();
  70263. this.L11 = BABYLON.Vector3.Zero();
  70264. this.L2_2 = BABYLON.Vector3.Zero();
  70265. this.L2_1 = BABYLON.Vector3.Zero();
  70266. this.L20 = BABYLON.Vector3.Zero();
  70267. this.L21 = BABYLON.Vector3.Zero();
  70268. this.L22 = BABYLON.Vector3.Zero();
  70269. }
  70270. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70271. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70272. var c = colorVector.scale(deltaSolidAngle);
  70273. this.L00 = this.L00.add(c.scale(0.282095));
  70274. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70275. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70276. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70277. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70278. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70279. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70280. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70281. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70282. };
  70283. SphericalHarmonics.prototype.scale = function (scale) {
  70284. this.L00 = this.L00.scale(scale);
  70285. this.L1_1 = this.L1_1.scale(scale);
  70286. this.L10 = this.L10.scale(scale);
  70287. this.L11 = this.L11.scale(scale);
  70288. this.L2_2 = this.L2_2.scale(scale);
  70289. this.L2_1 = this.L2_1.scale(scale);
  70290. this.L20 = this.L20.scale(scale);
  70291. this.L21 = this.L21.scale(scale);
  70292. this.L22 = this.L22.scale(scale);
  70293. };
  70294. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70295. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70296. //
  70297. // E_lm = A_l * L_lm
  70298. //
  70299. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70300. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70301. // the scaling factors are given in equation 9.
  70302. // Constant (Band 0)
  70303. this.L00 = this.L00.scale(3.141593);
  70304. // Linear (Band 1)
  70305. this.L1_1 = this.L1_1.scale(2.094395);
  70306. this.L10 = this.L10.scale(2.094395);
  70307. this.L11 = this.L11.scale(2.094395);
  70308. // Quadratic (Band 2)
  70309. this.L2_2 = this.L2_2.scale(0.785398);
  70310. this.L2_1 = this.L2_1.scale(0.785398);
  70311. this.L20 = this.L20.scale(0.785398);
  70312. this.L21 = this.L21.scale(0.785398);
  70313. this.L22 = this.L22.scale(0.785398);
  70314. };
  70315. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70316. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70317. // L = (1/pi) * E * rho
  70318. //
  70319. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70320. this.scale(1.0 / Math.PI);
  70321. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70322. // (The pixel shader must apply albedo after texture fetches, etc).
  70323. };
  70324. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70325. var result = new SphericalHarmonics();
  70326. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70327. result.L1_1 = polynomial.y.scale(0.977204);
  70328. result.L10 = polynomial.z.scale(0.977204);
  70329. result.L11 = polynomial.x.scale(0.977204);
  70330. result.L2_2 = polynomial.xy.scale(1.16538);
  70331. result.L2_1 = polynomial.yz.scale(1.16538);
  70332. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70333. result.L21 = polynomial.zx.scale(1.16538);
  70334. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70335. result.scale(Math.PI);
  70336. return result;
  70337. };
  70338. return SphericalHarmonics;
  70339. }());
  70340. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70341. })(BABYLON || (BABYLON = {}));
  70342. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70343. var BABYLON;
  70344. (function (BABYLON) {
  70345. var FileFaceOrientation = /** @class */ (function () {
  70346. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70347. this.name = name;
  70348. this.worldAxisForNormal = worldAxisForNormal;
  70349. this.worldAxisForFileX = worldAxisForFileX;
  70350. this.worldAxisForFileY = worldAxisForFileY;
  70351. }
  70352. return FileFaceOrientation;
  70353. }());
  70354. ;
  70355. /**
  70356. * Helper class dealing with the extraction of spherical polynomial dataArray
  70357. * from a cube map.
  70358. */
  70359. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70360. function CubeMapToSphericalPolynomialTools() {
  70361. }
  70362. /**
  70363. * Converts a texture to the according Spherical Polynomial data.
  70364. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70365. *
  70366. * @param texture The texture to extract the information from.
  70367. * @return The Spherical Polynomial data.
  70368. */
  70369. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70370. if (!texture.isCube) {
  70371. // Only supports cube Textures currently.
  70372. return null;
  70373. }
  70374. var size = texture.getSize().width;
  70375. var right = texture.readPixels(0);
  70376. var left = texture.readPixels(1);
  70377. var up;
  70378. var down;
  70379. if (texture.isRenderTarget) {
  70380. up = texture.readPixels(3);
  70381. down = texture.readPixels(2);
  70382. }
  70383. else {
  70384. up = texture.readPixels(2);
  70385. down = texture.readPixels(3);
  70386. }
  70387. var front = texture.readPixels(4);
  70388. var back = texture.readPixels(5);
  70389. var gammaSpace = texture.gammaSpace;
  70390. // Always read as RGBA.
  70391. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70392. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70393. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70394. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70395. }
  70396. var cubeInfo = {
  70397. size: size,
  70398. right: right,
  70399. left: left,
  70400. up: up,
  70401. down: down,
  70402. front: front,
  70403. back: back,
  70404. format: format,
  70405. type: type,
  70406. gammaSpace: gammaSpace,
  70407. };
  70408. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70409. };
  70410. /**
  70411. * Converts a cubemap to the according Spherical Polynomial data.
  70412. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70413. *
  70414. * @param cubeInfo The Cube map to extract the information from.
  70415. * @return The Spherical Polynomial data.
  70416. */
  70417. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70418. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70419. var totalSolidAngle = 0.0;
  70420. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70421. var du = 2.0 / cubeInfo.size;
  70422. var dv = du;
  70423. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70424. var minUV = du * 0.5 - 1.0;
  70425. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70426. var fileFace = this.FileFaces[faceIndex];
  70427. var dataArray = cubeInfo[fileFace.name];
  70428. var v = minUV;
  70429. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70430. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70431. // Because SP is still linear, so summation is fine in that basis.
  70432. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70433. for (var y = 0; y < cubeInfo.size; y++) {
  70434. var u = minUV;
  70435. for (var x = 0; x < cubeInfo.size; x++) {
  70436. // World direction (not normalised)
  70437. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70438. worldDirection.normalize();
  70439. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70440. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70441. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70442. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70443. // Handle Integer types.
  70444. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70445. r /= 255;
  70446. g /= 255;
  70447. b /= 255;
  70448. }
  70449. // Handle Gamma space textures.
  70450. if (cubeInfo.gammaSpace) {
  70451. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70452. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70453. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70454. }
  70455. var color = new BABYLON.Color3(r, g, b);
  70456. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70457. totalSolidAngle += deltaSolidAngle;
  70458. u += du;
  70459. }
  70460. v += dv;
  70461. }
  70462. }
  70463. // Solid angle for entire sphere is 4*pi
  70464. var sphereSolidAngle = 4.0 * Math.PI;
  70465. // Adjust the solid angle to allow for how many faces we processed.
  70466. var facesProcessed = 6.0;
  70467. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70468. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70469. // This is needed because the numerical integration over the cube uses a
  70470. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70471. // and also to compensate for accumulative error due to float precision in the summation.
  70472. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70473. sphericalHarmonics.scale(correctionFactor);
  70474. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70475. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70476. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70477. };
  70478. CubeMapToSphericalPolynomialTools.FileFaces = [
  70479. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70480. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70481. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70482. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70483. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70484. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70485. ];
  70486. return CubeMapToSphericalPolynomialTools;
  70487. }());
  70488. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70489. })(BABYLON || (BABYLON = {}));
  70490. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70491. var BABYLON;
  70492. (function (BABYLON) {
  70493. /**
  70494. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70495. */
  70496. var PanoramaToCubeMapTools = /** @class */ (function () {
  70497. function PanoramaToCubeMapTools() {
  70498. }
  70499. /**
  70500. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70501. *
  70502. * @param float32Array The source data.
  70503. * @param inputWidth The width of the input panorama.
  70504. * @param inputhHeight The height of the input panorama.
  70505. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70506. * @return The cubemap data
  70507. */
  70508. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70509. if (!float32Array) {
  70510. throw "ConvertPanoramaToCubemap: input cannot be null";
  70511. }
  70512. if (float32Array.length != inputWidth * inputHeight * 3) {
  70513. throw "ConvertPanoramaToCubemap: input size is wrong";
  70514. }
  70515. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70516. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70517. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70518. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70519. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70520. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70521. return {
  70522. front: textureFront,
  70523. back: textureBack,
  70524. left: textureLeft,
  70525. right: textureRight,
  70526. up: textureUp,
  70527. down: textureDown,
  70528. size: size,
  70529. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70530. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70531. gammaSpace: false,
  70532. };
  70533. };
  70534. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70535. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70536. var textureArray = new Float32Array(buffer);
  70537. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70538. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70539. var dy = 1 / texSize;
  70540. var fy = 0;
  70541. for (var y = 0; y < texSize; y++) {
  70542. var xv1 = faceData[0];
  70543. var xv2 = faceData[2];
  70544. for (var x = 0; x < texSize; x++) {
  70545. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70546. v.normalize();
  70547. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70548. // 3 channels per pixels
  70549. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70550. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70551. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70552. xv1 = xv1.add(rotDX1);
  70553. xv2 = xv2.add(rotDX2);
  70554. }
  70555. fy += dy;
  70556. }
  70557. return textureArray;
  70558. };
  70559. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70560. var theta = Math.atan2(vDir.z, vDir.x);
  70561. var phi = Math.acos(vDir.y);
  70562. while (theta < -Math.PI)
  70563. theta += 2 * Math.PI;
  70564. while (theta > Math.PI)
  70565. theta -= 2 * Math.PI;
  70566. var dx = theta / Math.PI;
  70567. var dy = phi / Math.PI;
  70568. // recenter.
  70569. dx = dx * 0.5 + 0.5;
  70570. var px = Math.round(dx * inputWidth);
  70571. if (px < 0)
  70572. px = 0;
  70573. else if (px >= inputWidth)
  70574. px = inputWidth - 1;
  70575. var py = Math.round(dy * inputHeight);
  70576. if (py < 0)
  70577. py = 0;
  70578. else if (py >= inputHeight)
  70579. py = inputHeight - 1;
  70580. var inputY = (inputHeight - py - 1);
  70581. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70582. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70583. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70584. return {
  70585. r: r,
  70586. g: g,
  70587. b: b
  70588. };
  70589. };
  70590. PanoramaToCubeMapTools.FACE_FRONT = [
  70591. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70592. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70593. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70594. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70595. ];
  70596. PanoramaToCubeMapTools.FACE_BACK = [
  70597. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70598. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70599. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70600. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70601. ];
  70602. PanoramaToCubeMapTools.FACE_RIGHT = [
  70603. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70604. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70605. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70606. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70607. ];
  70608. PanoramaToCubeMapTools.FACE_LEFT = [
  70609. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70610. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70611. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70612. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70613. ];
  70614. PanoramaToCubeMapTools.FACE_DOWN = [
  70615. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70616. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70617. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70618. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70619. ];
  70620. PanoramaToCubeMapTools.FACE_UP = [
  70621. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70622. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70623. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70624. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70625. ];
  70626. return PanoramaToCubeMapTools;
  70627. }());
  70628. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70629. })(BABYLON || (BABYLON = {}));
  70630. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70631. var BABYLON;
  70632. (function (BABYLON) {
  70633. ;
  70634. /**
  70635. * This groups tools to convert HDR texture to native colors array.
  70636. */
  70637. var HDRTools = /** @class */ (function () {
  70638. function HDRTools() {
  70639. }
  70640. HDRTools.Ldexp = function (mantissa, exponent) {
  70641. if (exponent > 1023) {
  70642. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70643. }
  70644. if (exponent < -1074) {
  70645. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70646. }
  70647. return mantissa * Math.pow(2, exponent);
  70648. };
  70649. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70650. if (exponent > 0) {
  70651. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70652. float32array[index + 0] = red * exponent;
  70653. float32array[index + 1] = green * exponent;
  70654. float32array[index + 2] = blue * exponent;
  70655. }
  70656. else {
  70657. float32array[index + 0] = 0;
  70658. float32array[index + 1] = 0;
  70659. float32array[index + 2] = 0;
  70660. }
  70661. };
  70662. HDRTools.readStringLine = function (uint8array, startIndex) {
  70663. var line = "";
  70664. var character = "";
  70665. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70666. character = String.fromCharCode(uint8array[i]);
  70667. if (character == "\n") {
  70668. break;
  70669. }
  70670. line += character;
  70671. }
  70672. return line;
  70673. };
  70674. /**
  70675. * Reads header information from an RGBE texture stored in a native array.
  70676. * More information on this format are available here:
  70677. * https://en.wikipedia.org/wiki/RGBE_image_format
  70678. *
  70679. * @param uint8array The binary file stored in native array.
  70680. * @return The header information.
  70681. */
  70682. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70683. var height = 0;
  70684. var width = 0;
  70685. var line = this.readStringLine(uint8array, 0);
  70686. if (line[0] != '#' || line[1] != '?') {
  70687. throw "Bad HDR Format.";
  70688. }
  70689. var endOfHeader = false;
  70690. var findFormat = false;
  70691. var lineIndex = 0;
  70692. do {
  70693. lineIndex += (line.length + 1);
  70694. line = this.readStringLine(uint8array, lineIndex);
  70695. if (line == "FORMAT=32-bit_rle_rgbe") {
  70696. findFormat = true;
  70697. }
  70698. else if (line.length == 0) {
  70699. endOfHeader = true;
  70700. }
  70701. } while (!endOfHeader);
  70702. if (!findFormat) {
  70703. throw "HDR Bad header format, unsupported FORMAT";
  70704. }
  70705. lineIndex += (line.length + 1);
  70706. line = this.readStringLine(uint8array, lineIndex);
  70707. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70708. var match = sizeRegexp.exec(line);
  70709. // TODO. Support +Y and -X if needed.
  70710. if (!match || match.length < 3) {
  70711. throw "HDR Bad header format, no size";
  70712. }
  70713. width = parseInt(match[2]);
  70714. height = parseInt(match[1]);
  70715. if (width < 8 || width > 0x7fff) {
  70716. throw "HDR Bad header format, unsupported size";
  70717. }
  70718. lineIndex += (line.length + 1);
  70719. return {
  70720. height: height,
  70721. width: width,
  70722. dataPosition: lineIndex
  70723. };
  70724. };
  70725. /**
  70726. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70727. * This RGBE texture needs to store the information as a panorama.
  70728. *
  70729. * More information on this format are available here:
  70730. * https://en.wikipedia.org/wiki/RGBE_image_format
  70731. *
  70732. * @param buffer The binary file stored in an array buffer.
  70733. * @param size The expected size of the extracted cubemap.
  70734. * @return The Cube Map information.
  70735. */
  70736. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70737. var uint8array = new Uint8Array(buffer);
  70738. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70739. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70740. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70741. return cubeMapData;
  70742. };
  70743. /**
  70744. * Returns the pixels data extracted from an RGBE texture.
  70745. * This pixels will be stored left to right up to down in the R G B order in one array.
  70746. *
  70747. * More information on this format are available here:
  70748. * https://en.wikipedia.org/wiki/RGBE_image_format
  70749. *
  70750. * @param uint8array The binary file stored in an array buffer.
  70751. * @param hdrInfo The header information of the file.
  70752. * @return The pixels data in RGB right to left up to down order.
  70753. */
  70754. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70755. // Keep for multi format supports.
  70756. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70757. };
  70758. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70759. var num_scanlines = hdrInfo.height;
  70760. var scanline_width = hdrInfo.width;
  70761. var a, b, c, d, count;
  70762. var dataIndex = hdrInfo.dataPosition;
  70763. var index = 0, endIndex = 0, i = 0;
  70764. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70765. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70766. // 3 channels of 4 bytes per pixel in float.
  70767. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70768. var resultArray = new Float32Array(resultBuffer);
  70769. // read in each successive scanline
  70770. while (num_scanlines > 0) {
  70771. a = uint8array[dataIndex++];
  70772. b = uint8array[dataIndex++];
  70773. c = uint8array[dataIndex++];
  70774. d = uint8array[dataIndex++];
  70775. if (a != 2 || b != 2 || (c & 0x80)) {
  70776. // this file is not run length encoded
  70777. throw "HDR Bad header format, not RLE";
  70778. }
  70779. if (((c << 8) | d) != scanline_width) {
  70780. throw "HDR Bad header format, wrong scan line width";
  70781. }
  70782. index = 0;
  70783. // read each of the four channels for the scanline into the buffer
  70784. for (i = 0; i < 4; i++) {
  70785. endIndex = (i + 1) * scanline_width;
  70786. while (index < endIndex) {
  70787. a = uint8array[dataIndex++];
  70788. b = uint8array[dataIndex++];
  70789. if (a > 128) {
  70790. // a run of the same value
  70791. count = a - 128;
  70792. if ((count == 0) || (count > endIndex - index)) {
  70793. throw "HDR Bad Format, bad scanline data (run)";
  70794. }
  70795. while (count-- > 0) {
  70796. scanLineArray[index++] = b;
  70797. }
  70798. }
  70799. else {
  70800. // a non-run
  70801. count = a;
  70802. if ((count == 0) || (count > endIndex - index)) {
  70803. throw "HDR Bad Format, bad scanline data (non-run)";
  70804. }
  70805. scanLineArray[index++] = b;
  70806. if (--count > 0) {
  70807. for (var j = 0; j < count; j++) {
  70808. scanLineArray[index++] = uint8array[dataIndex++];
  70809. }
  70810. }
  70811. }
  70812. }
  70813. }
  70814. // now convert data from buffer into floats
  70815. for (i = 0; i < scanline_width; i++) {
  70816. a = scanLineArray[i];
  70817. b = scanLineArray[i + scanline_width];
  70818. c = scanLineArray[i + 2 * scanline_width];
  70819. d = scanLineArray[i + 3 * scanline_width];
  70820. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70821. }
  70822. num_scanlines--;
  70823. }
  70824. return resultArray;
  70825. };
  70826. return HDRTools;
  70827. }());
  70828. BABYLON.HDRTools = HDRTools;
  70829. })(BABYLON || (BABYLON = {}));
  70830. //# sourceMappingURL=babylon.hdr.js.map
  70831. var BABYLON;
  70832. (function (BABYLON) {
  70833. /**
  70834. * This represents a texture coming from an HDR input.
  70835. *
  70836. * The only supported format is currently panorama picture stored in RGBE format.
  70837. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70838. */
  70839. var HDRCubeTexture = /** @class */ (function (_super) {
  70840. __extends(HDRCubeTexture, _super);
  70841. /**
  70842. * Instantiates an HDRTexture from the following parameters.
  70843. *
  70844. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70845. * @param scene The scene the texture will be used in
  70846. * @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.
  70847. * @param noMipmap Forces to not generate the mipmap if true
  70848. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70849. * @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)
  70850. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70851. */
  70852. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70853. if (noMipmap === void 0) { noMipmap = false; }
  70854. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70855. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70856. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70857. if (onLoad === void 0) { onLoad = null; }
  70858. if (onError === void 0) { onError = null; }
  70859. var _this = _super.call(this, scene) || this;
  70860. _this._useInGammaSpace = false;
  70861. _this._generateHarmonics = true;
  70862. _this._isBABYLONPreprocessed = false;
  70863. _this._onLoad = null;
  70864. _this._onError = null;
  70865. /**
  70866. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70867. */
  70868. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70869. /**
  70870. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70871. * This is usefull at run time to apply the good shader.
  70872. */
  70873. _this.isPMREM = false;
  70874. _this._isBlocking = true;
  70875. if (!url) {
  70876. return _this;
  70877. }
  70878. _this.name = url;
  70879. _this.url = url;
  70880. _this.hasAlpha = false;
  70881. _this.isCube = true;
  70882. _this._textureMatrix = BABYLON.Matrix.Identity();
  70883. _this._onLoad = onLoad;
  70884. _this._onError = onError;
  70885. _this.gammaSpace = false;
  70886. var caps = scene.getEngine().getCaps();
  70887. if (size) {
  70888. _this._isBABYLONPreprocessed = false;
  70889. _this._noMipmap = noMipmap;
  70890. _this._size = size;
  70891. _this._useInGammaSpace = useInGammaSpace;
  70892. _this._usePMREMGenerator = usePMREMGenerator &&
  70893. caps.textureLOD &&
  70894. caps.textureFloat &&
  70895. !_this._useInGammaSpace;
  70896. }
  70897. else {
  70898. _this._isBABYLONPreprocessed = true;
  70899. _this._noMipmap = false;
  70900. _this._useInGammaSpace = false;
  70901. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  70902. !_this._useInGammaSpace;
  70903. }
  70904. _this.isPMREM = _this._usePMREMGenerator;
  70905. _this._texture = _this._getFromCache(url, _this._noMipmap);
  70906. if (!_this._texture) {
  70907. if (!scene.useDelayedTextureLoading) {
  70908. _this.loadTexture();
  70909. }
  70910. else {
  70911. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70912. }
  70913. }
  70914. return _this;
  70915. }
  70916. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  70917. /**
  70918. * Gets wether or not the texture is blocking during loading.
  70919. */
  70920. get: function () {
  70921. return this._isBlocking;
  70922. },
  70923. /**
  70924. * Sets wether or not the texture is blocking during loading.
  70925. */
  70926. set: function (value) {
  70927. this._isBlocking = value;
  70928. },
  70929. enumerable: true,
  70930. configurable: true
  70931. });
  70932. /**
  70933. * Occurs when the file is a preprocessed .babylon.hdr file.
  70934. */
  70935. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  70936. var _this = this;
  70937. var mipLevels = 0;
  70938. var floatArrayView = null;
  70939. var scene = this.getScene();
  70940. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  70941. var mips = new Array();
  70942. if (!floatArrayView) {
  70943. return mips;
  70944. }
  70945. var startIndex = 30;
  70946. for (var level = 0; level < mipLevels; level++) {
  70947. mips.push([]);
  70948. // Fill each pixel of the mip level.
  70949. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  70950. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70951. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  70952. mips[level].push(faceData);
  70953. startIndex += faceSize;
  70954. }
  70955. }
  70956. return mips;
  70957. } : null;
  70958. var callback = function (buffer) {
  70959. var scene = _this.getScene();
  70960. if (!scene) {
  70961. return null;
  70962. }
  70963. // Create Native Array Views
  70964. var intArrayView = new Int32Array(buffer);
  70965. floatArrayView = new Float32Array(buffer);
  70966. // Fill header.
  70967. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  70968. _this._size = intArrayView[1]; // CubeMap max mip face size.
  70969. // Update Texture Information.
  70970. if (!_this._texture) {
  70971. return null;
  70972. }
  70973. _this._texture.updateSize(_this._size, _this._size);
  70974. // Fill polynomial information.
  70975. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  70976. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  70977. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  70978. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  70979. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  70980. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  70981. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  70982. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  70983. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  70984. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  70985. _this.sphericalPolynomial = sphericalPolynomial;
  70986. // Fill pixel data.
  70987. mipLevels = intArrayView[29]; // Number of mip levels.
  70988. var startIndex = 30;
  70989. var data = [];
  70990. var faceSize = Math.pow(_this._size, 2) * 3;
  70991. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70992. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  70993. startIndex += faceSize;
  70994. }
  70995. var results = [];
  70996. var byteArray = null;
  70997. // Push each faces.
  70998. for (var k = 0; k < 6; k++) {
  70999. var dataFace = null;
  71000. // To be deprecated.
  71001. if (version === 1) {
  71002. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71003. dataFace = data[j];
  71004. }
  71005. // If special cases.
  71006. if (!mipmapGenerator && dataFace) {
  71007. if (!scene.getEngine().getCaps().textureFloat) {
  71008. // 3 channels of 1 bytes per pixel in bytes.
  71009. var byteBuffer = new ArrayBuffer(faceSize);
  71010. byteArray = new Uint8Array(byteBuffer);
  71011. }
  71012. for (var i = 0; i < _this._size * _this._size; i++) {
  71013. // Put in gamma space if requested.
  71014. if (_this._useInGammaSpace) {
  71015. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71016. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71017. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71018. }
  71019. // Convert to int texture for fallback.
  71020. if (byteArray) {
  71021. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71022. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71023. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71024. // May use luminance instead if the result is not accurate.
  71025. var max = Math.max(Math.max(r, g), b);
  71026. if (max > 255) {
  71027. var scale = 255 / max;
  71028. r *= scale;
  71029. g *= scale;
  71030. b *= scale;
  71031. }
  71032. byteArray[(i * 3) + 0] = r;
  71033. byteArray[(i * 3) + 1] = g;
  71034. byteArray[(i * 3) + 2] = b;
  71035. }
  71036. }
  71037. }
  71038. // Fill the array accordingly.
  71039. if (byteArray) {
  71040. results.push(byteArray);
  71041. }
  71042. else {
  71043. results.push(dataFace);
  71044. }
  71045. }
  71046. return results;
  71047. };
  71048. if (scene) {
  71049. 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);
  71050. }
  71051. };
  71052. /**
  71053. * Occurs when the file is raw .hdr file.
  71054. */
  71055. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71056. var _this = this;
  71057. var callback = function (buffer) {
  71058. var scene = _this.getScene();
  71059. if (!scene) {
  71060. return null;
  71061. }
  71062. // Extract the raw linear data.
  71063. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71064. // Generate harmonics if needed.
  71065. if (_this._generateHarmonics) {
  71066. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71067. _this.sphericalPolynomial = sphericalPolynomial;
  71068. }
  71069. var results = [];
  71070. var byteArray = null;
  71071. // Push each faces.
  71072. for (var j = 0; j < 6; j++) {
  71073. // Create uintarray fallback.
  71074. if (!scene.getEngine().getCaps().textureFloat) {
  71075. // 3 channels of 1 bytes per pixel in bytes.
  71076. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71077. byteArray = new Uint8Array(byteBuffer);
  71078. }
  71079. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71080. // If special cases.
  71081. if (_this._useInGammaSpace || byteArray) {
  71082. for (var i = 0; i < _this._size * _this._size; i++) {
  71083. // Put in gamma space if requested.
  71084. if (_this._useInGammaSpace) {
  71085. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71086. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71087. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71088. }
  71089. // Convert to int texture for fallback.
  71090. if (byteArray) {
  71091. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71092. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71093. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71094. // May use luminance instead if the result is not accurate.
  71095. var max = Math.max(Math.max(r, g), b);
  71096. if (max > 255) {
  71097. var scale = 255 / max;
  71098. r *= scale;
  71099. g *= scale;
  71100. b *= scale;
  71101. }
  71102. byteArray[(i * 3) + 0] = r;
  71103. byteArray[(i * 3) + 1] = g;
  71104. byteArray[(i * 3) + 2] = b;
  71105. }
  71106. }
  71107. }
  71108. if (byteArray) {
  71109. results.push(byteArray);
  71110. }
  71111. else {
  71112. results.push(dataFace);
  71113. }
  71114. }
  71115. return results;
  71116. };
  71117. var mipmapGenerator = null;
  71118. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71119. // if (!this._noMipmap &&
  71120. // this._usePMREMGenerator) {
  71121. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71122. // // Custom setup of the generator matching with the PBR shader values.
  71123. // var generator = new BABYLON.PMREMGenerator(data,
  71124. // this._size,
  71125. // this._size,
  71126. // 0,
  71127. // 3,
  71128. // this.getScene().getEngine().getCaps().textureFloat,
  71129. // 2048,
  71130. // 0.25,
  71131. // false,
  71132. // true);
  71133. // return generator.filterCubeMap();
  71134. // };
  71135. // }
  71136. var scene = this.getScene();
  71137. if (scene) {
  71138. 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);
  71139. }
  71140. };
  71141. /**
  71142. * Starts the loading process of the texture.
  71143. */
  71144. HDRCubeTexture.prototype.loadTexture = function () {
  71145. if (this._isBABYLONPreprocessed) {
  71146. this.loadBabylonTexture();
  71147. }
  71148. else {
  71149. this.loadHDRTexture();
  71150. }
  71151. };
  71152. HDRCubeTexture.prototype.clone = function () {
  71153. var scene = this.getScene();
  71154. if (!scene) {
  71155. return this;
  71156. }
  71157. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71158. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71159. // Base texture
  71160. newTexture.level = this.level;
  71161. newTexture.wrapU = this.wrapU;
  71162. newTexture.wrapV = this.wrapV;
  71163. newTexture.coordinatesIndex = this.coordinatesIndex;
  71164. newTexture.coordinatesMode = this.coordinatesMode;
  71165. return newTexture;
  71166. };
  71167. // Methods
  71168. HDRCubeTexture.prototype.delayLoad = function () {
  71169. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71170. return;
  71171. }
  71172. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71173. this._texture = this._getFromCache(this.url, this._noMipmap);
  71174. if (!this._texture) {
  71175. this.loadTexture();
  71176. }
  71177. };
  71178. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71179. return this._textureMatrix;
  71180. };
  71181. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71182. this._textureMatrix = value;
  71183. };
  71184. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71185. var texture = null;
  71186. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71187. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71188. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71189. texture.name = parsedTexture.name;
  71190. texture.hasAlpha = parsedTexture.hasAlpha;
  71191. texture.level = parsedTexture.level;
  71192. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71193. texture.isBlocking = parsedTexture.isBlocking;
  71194. }
  71195. return texture;
  71196. };
  71197. HDRCubeTexture.prototype.serialize = function () {
  71198. if (!this.name) {
  71199. return null;
  71200. }
  71201. var serializationObject = {};
  71202. serializationObject.name = this.name;
  71203. serializationObject.hasAlpha = this.hasAlpha;
  71204. serializationObject.isCube = true;
  71205. serializationObject.level = this.level;
  71206. serializationObject.size = this._size;
  71207. serializationObject.coordinatesMode = this.coordinatesMode;
  71208. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71209. serializationObject.generateHarmonics = this._generateHarmonics;
  71210. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71211. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71212. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71213. serializationObject.noMipmap = this._noMipmap;
  71214. serializationObject.isBlocking = this._isBlocking;
  71215. return serializationObject;
  71216. };
  71217. /**
  71218. * Saves as a file the data contained in the texture in a binary format.
  71219. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71220. * as the spherical used in the lighting.
  71221. * @param url The HDR file url.
  71222. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71223. * @param onError Method called if any error happens during download.
  71224. * @return The packed binary data.
  71225. */
  71226. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71227. if (onError === void 0) { onError = null; }
  71228. var callback = function (buffer) {
  71229. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71230. // Returns a URL you can use as a href.
  71231. var objUrl = window.URL.createObjectURL(data);
  71232. // Simulates a link to it and click to dowload.
  71233. var a = document.createElement("a");
  71234. document.body.appendChild(a);
  71235. a.style.display = "none";
  71236. a.href = objUrl;
  71237. a.download = "envmap.babylon.hdr";
  71238. a.click();
  71239. };
  71240. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71241. };
  71242. /**
  71243. * Serializes the data contained in the texture in a binary format.
  71244. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71245. * as the spherical used in the lighting.
  71246. * @param url The HDR file url.
  71247. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71248. * @param onError Method called if any error happens during download.
  71249. * @return The packed binary data.
  71250. */
  71251. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71252. if (onError === void 0) { onError = null; }
  71253. // Needs the url tho create the texture.
  71254. if (!url) {
  71255. return;
  71256. }
  71257. // Check Power of two size.
  71258. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71259. return;
  71260. }
  71261. // Coming Back in 3.x.
  71262. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71263. };
  71264. HDRCubeTexture._facesMapping = [
  71265. "right",
  71266. "left",
  71267. "up",
  71268. "down",
  71269. "front",
  71270. "back"
  71271. ];
  71272. return HDRCubeTexture;
  71273. }(BABYLON.BaseTexture));
  71274. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71275. })(BABYLON || (BABYLON = {}));
  71276. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71277. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71278. // Huge respect for a such great lib.
  71279. // Earcut license:
  71280. // Copyright (c) 2016, Mapbox
  71281. //
  71282. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71283. // with or without fee is hereby granted, provided that the above copyright notice
  71284. // and this permission notice appear in all copies.
  71285. //
  71286. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71287. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71288. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71289. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71290. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71291. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71292. // THIS SOFTWARE.
  71293. var Earcut;
  71294. (function (Earcut) {
  71295. /**
  71296. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71297. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71298. * @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).
  71299. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71300. */
  71301. function earcut(data, holeIndices, dim) {
  71302. dim = dim || 2;
  71303. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71304. if (!outerNode)
  71305. return triangles;
  71306. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71307. if (hasHoles)
  71308. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71309. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71310. if (data.length > 80 * dim) {
  71311. minX = maxX = data[0];
  71312. minY = maxY = data[1];
  71313. for (var i = dim; i < outerLen; i += dim) {
  71314. x = data[i];
  71315. y = data[i + 1];
  71316. if (x < minX)
  71317. minX = x;
  71318. if (y < minY)
  71319. minY = y;
  71320. if (x > maxX)
  71321. maxX = x;
  71322. if (y > maxY)
  71323. maxY = y;
  71324. }
  71325. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71326. size = Math.max(maxX - minX, maxY - minY);
  71327. }
  71328. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71329. return triangles;
  71330. }
  71331. Earcut.earcut = earcut;
  71332. var Node = /** @class */ (function () {
  71333. function Node(i, x, y) {
  71334. this.i = i;
  71335. this.x = x;
  71336. this.y = y;
  71337. this.prev = null;
  71338. this.next = null;
  71339. this.z = null;
  71340. this.prevZ = null;
  71341. this.nextZ = null;
  71342. this.steiner = false;
  71343. }
  71344. return Node;
  71345. }());
  71346. // create a circular doubly linked list from polygon points in the specified winding order
  71347. function linkedList(data, start, end, dim, clockwise) {
  71348. var i, last = null;
  71349. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71350. for (i = start; i < end; i += dim)
  71351. last = insertNode(i, data[i], data[i + 1], last);
  71352. }
  71353. else {
  71354. for (i = end - dim; i >= start; i -= dim)
  71355. last = insertNode(i, data[i], data[i + 1], last);
  71356. }
  71357. if (last && equals(last, last.next)) {
  71358. removeNode(last);
  71359. last = last.next;
  71360. }
  71361. return last;
  71362. }
  71363. // eliminate colinear or duplicate points
  71364. function filterPoints(start, end) {
  71365. if (!start)
  71366. return start;
  71367. if (!end)
  71368. end = start;
  71369. var p = start, again;
  71370. do {
  71371. again = false;
  71372. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71373. removeNode(p);
  71374. p = end = p.prev;
  71375. if (p === p.next)
  71376. return undefined;
  71377. again = true;
  71378. }
  71379. else {
  71380. p = p.next;
  71381. }
  71382. } while (again || p !== end);
  71383. return end;
  71384. }
  71385. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71386. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71387. if (!ear)
  71388. return;
  71389. // interlink polygon nodes in z-order
  71390. if (!pass && size)
  71391. indexCurve(ear, minX, minY, size);
  71392. var stop = ear, prev, next;
  71393. // iterate through ears, slicing them one by one
  71394. while (ear.prev !== ear.next) {
  71395. prev = ear.prev;
  71396. next = ear.next;
  71397. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71398. // cut off the triangle
  71399. triangles.push(prev.i / dim);
  71400. triangles.push(ear.i / dim);
  71401. triangles.push(next.i / dim);
  71402. removeNode(ear);
  71403. // skipping the next vertice leads to less sliver triangles
  71404. ear = next.next;
  71405. stop = next.next;
  71406. continue;
  71407. }
  71408. ear = next;
  71409. // if we looped through the whole remaining polygon and can't find any more ears
  71410. if (ear === stop) {
  71411. // try filtering points and slicing again
  71412. if (!pass) {
  71413. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71414. // if this didn't work, try curing all small self-intersections locally
  71415. }
  71416. else if (pass === 1) {
  71417. ear = cureLocalIntersections(ear, triangles, dim);
  71418. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71419. // as a last resort, try splitting the remaining polygon into two
  71420. }
  71421. else if (pass === 2) {
  71422. splitEarcut(ear, triangles, dim, minX, minY, size);
  71423. }
  71424. break;
  71425. }
  71426. }
  71427. }
  71428. // check whether a polygon node forms a valid ear with adjacent nodes
  71429. function isEar(ear) {
  71430. var a = ear.prev, b = ear, c = ear.next;
  71431. if (area(a, b, c) >= 0)
  71432. return false; // reflex, can't be an ear
  71433. // now make sure we don't have other points inside the potential ear
  71434. var p = ear.next.next;
  71435. while (p !== ear.prev) {
  71436. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71437. area(p.prev, p, p.next) >= 0)
  71438. return false;
  71439. p = p.next;
  71440. }
  71441. return true;
  71442. }
  71443. function isEarHashed(ear, minX, minY, size) {
  71444. var a = ear.prev, b = ear, c = ear.next;
  71445. if (area(a, b, c) >= 0)
  71446. return false; // reflex, can't be an ear
  71447. // triangle bbox; min & max are calculated like this for speed
  71448. 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);
  71449. // z-order range for the current triangle bbox;
  71450. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71451. // first look for points inside the triangle in increasing z-order
  71452. var p = ear.nextZ;
  71453. while (p && p.z <= maxZ) {
  71454. if (p !== ear.prev &&
  71455. p !== ear.next &&
  71456. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71457. area(p.prev, p, p.next) >= 0)
  71458. return false;
  71459. p = p.nextZ;
  71460. }
  71461. // then look for points in decreasing z-order
  71462. p = ear.prevZ;
  71463. while (p && p.z >= minZ) {
  71464. if (p !== ear.prev &&
  71465. p !== ear.next &&
  71466. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71467. area(p.prev, p, p.next) >= 0)
  71468. return false;
  71469. p = p.prevZ;
  71470. }
  71471. return true;
  71472. }
  71473. // go through all polygon nodes and cure small local self-intersections
  71474. function cureLocalIntersections(start, triangles, dim) {
  71475. var p = start;
  71476. do {
  71477. var a = p.prev, b = p.next.next;
  71478. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71479. triangles.push(a.i / dim);
  71480. triangles.push(p.i / dim);
  71481. triangles.push(b.i / dim);
  71482. // remove two nodes involved
  71483. removeNode(p);
  71484. removeNode(p.next);
  71485. p = start = b;
  71486. }
  71487. p = p.next;
  71488. } while (p !== start);
  71489. return p;
  71490. }
  71491. // try splitting polygon into two and triangulate them independently
  71492. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71493. // look for a valid diagonal that divides the polygon into two
  71494. var a = start;
  71495. do {
  71496. var b = a.next.next;
  71497. while (b !== a.prev) {
  71498. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71499. // split the polygon in two by the diagonal
  71500. var c = splitPolygon(a, b);
  71501. // filter colinear points around the cuts
  71502. a = filterPoints(a, a.next);
  71503. c = filterPoints(c, c.next);
  71504. // run earcut on each half
  71505. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71506. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71507. return;
  71508. }
  71509. b = b.next;
  71510. }
  71511. a = a.next;
  71512. } while (a !== start);
  71513. }
  71514. // link every hole into the outer loop, producing a single-ring polygon without holes
  71515. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71516. var queue = [], i, len, start, end, list;
  71517. for (i = 0, len = holeIndices.length; i < len; i++) {
  71518. start = holeIndices[i] * dim;
  71519. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71520. list = linkedList(data, start, end, dim, false);
  71521. if (list === list.next)
  71522. list.steiner = true;
  71523. queue.push(getLeftmost(list));
  71524. }
  71525. queue.sort(compareX);
  71526. // process holes from left to right
  71527. for (i = 0; i < queue.length; i++) {
  71528. eliminateHole(queue[i], outerNode);
  71529. outerNode = filterPoints(outerNode, outerNode.next);
  71530. }
  71531. return outerNode;
  71532. }
  71533. function compareX(a, b) {
  71534. return a.x - b.x;
  71535. }
  71536. // find a bridge between vertices that connects hole with an outer ring and and link it
  71537. function eliminateHole(hole, outerNode) {
  71538. outerNode = findHoleBridge(hole, outerNode);
  71539. if (outerNode) {
  71540. var b = splitPolygon(outerNode, hole);
  71541. filterPoints(b, b.next);
  71542. }
  71543. }
  71544. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71545. function findHoleBridge(hole, outerNode) {
  71546. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71547. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71548. // segment's endpoint with lesser x will be potential connection point
  71549. do {
  71550. if (hy <= p.y && hy >= p.next.y) {
  71551. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71552. if (x <= hx && x > qx) {
  71553. qx = x;
  71554. if (x === hx) {
  71555. if (hy === p.y)
  71556. return p;
  71557. if (hy === p.next.y)
  71558. return p.next;
  71559. }
  71560. m = p.x < p.next.x ? p : p.next;
  71561. }
  71562. }
  71563. p = p.next;
  71564. } while (p !== outerNode);
  71565. if (!m)
  71566. return null;
  71567. if (hx === qx)
  71568. return m.prev; // hole touches outer segment; pick lower endpoint
  71569. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71570. // if there are no points found, we have a valid connection;
  71571. // otherwise choose the point of the minimum angle with the ray as connection point
  71572. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71573. p = m.next;
  71574. while (p !== stop) {
  71575. if (hx >= p.x &&
  71576. p.x >= mx &&
  71577. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71578. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71579. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71580. m = p;
  71581. tanMin = tan;
  71582. }
  71583. }
  71584. p = p.next;
  71585. }
  71586. return m;
  71587. }
  71588. // interlink polygon nodes in z-order
  71589. function indexCurve(start, minX, minY, size) {
  71590. var p = start;
  71591. do {
  71592. if (p.z === null)
  71593. p.z = zOrder(p.x, p.y, minX, minY, size);
  71594. p.prevZ = p.prev;
  71595. p.nextZ = p.next;
  71596. p = p.next;
  71597. } while (p !== start);
  71598. p.prevZ.nextZ = null;
  71599. p.prevZ = null;
  71600. sortLinked(p);
  71601. }
  71602. // Simon Tatham's linked list merge sort algorithm
  71603. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71604. function sortLinked(list) {
  71605. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71606. do {
  71607. p = list;
  71608. list = null;
  71609. tail = null;
  71610. numMerges = 0;
  71611. while (p) {
  71612. numMerges++;
  71613. q = p;
  71614. pSize = 0;
  71615. for (i = 0; i < inSize; i++) {
  71616. pSize++;
  71617. q = q.nextZ;
  71618. if (!q)
  71619. break;
  71620. }
  71621. qSize = inSize;
  71622. while (pSize > 0 || (qSize > 0 && q)) {
  71623. if (pSize === 0) {
  71624. e = q;
  71625. q = q.nextZ;
  71626. qSize--;
  71627. }
  71628. else if (qSize === 0 || !q) {
  71629. e = p;
  71630. p = p.nextZ;
  71631. pSize--;
  71632. }
  71633. else if (p.z <= q.z) {
  71634. e = p;
  71635. p = p.nextZ;
  71636. pSize--;
  71637. }
  71638. else {
  71639. e = q;
  71640. q = q.nextZ;
  71641. qSize--;
  71642. }
  71643. if (tail)
  71644. tail.nextZ = e;
  71645. else
  71646. list = e;
  71647. e.prevZ = tail;
  71648. tail = e;
  71649. }
  71650. p = q;
  71651. }
  71652. tail.nextZ = null;
  71653. inSize *= 2;
  71654. } while (numMerges > 1);
  71655. return list;
  71656. }
  71657. // z-order of a point given coords and size of the data bounding box
  71658. function zOrder(x, y, minX, minY, size) {
  71659. // coords are transformed into non-negative 15-bit integer range
  71660. x = 32767 * (x - minX) / size;
  71661. y = 32767 * (y - minY) / size;
  71662. x = (x | (x << 8)) & 0x00FF00FF;
  71663. x = (x | (x << 4)) & 0x0F0F0F0F;
  71664. x = (x | (x << 2)) & 0x33333333;
  71665. x = (x | (x << 1)) & 0x55555555;
  71666. y = (y | (y << 8)) & 0x00FF00FF;
  71667. y = (y | (y << 4)) & 0x0F0F0F0F;
  71668. y = (y | (y << 2)) & 0x33333333;
  71669. y = (y | (y << 1)) & 0x55555555;
  71670. return x | (y << 1);
  71671. }
  71672. // find the leftmost node of a polygon ring
  71673. function getLeftmost(start) {
  71674. var p = start, leftmost = start;
  71675. do {
  71676. if (p.x < leftmost.x)
  71677. leftmost = p;
  71678. p = p.next;
  71679. } while (p !== start);
  71680. return leftmost;
  71681. }
  71682. // check if a point lies within a convex triangle
  71683. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71684. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71685. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71686. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71687. }
  71688. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71689. function isValidDiagonal(a, b) {
  71690. return a.next.i !== b.i &&
  71691. a.prev.i !== b.i &&
  71692. !intersectsPolygon(a, b) &&
  71693. locallyInside(a, b) &&
  71694. locallyInside(b, a) &&
  71695. middleInside(a, b);
  71696. }
  71697. // signed area of a triangle
  71698. function area(p, q, r) {
  71699. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71700. }
  71701. // check if two points are equal
  71702. function equals(p1, p2) {
  71703. return p1.x === p2.x && p1.y === p2.y;
  71704. }
  71705. // check if two segments intersect
  71706. function intersects(p1, q1, p2, q2) {
  71707. if ((equals(p1, q1) && equals(p2, q2)) ||
  71708. (equals(p1, q2) && equals(p2, q1)))
  71709. return true;
  71710. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71711. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71712. }
  71713. // check if a polygon diagonal intersects any polygon segments
  71714. function intersectsPolygon(a, b) {
  71715. var p = a;
  71716. do {
  71717. if (p.i !== a.i &&
  71718. p.next.i !== a.i &&
  71719. p.i !== b.i &&
  71720. p.next.i !== b.i &&
  71721. intersects(p, p.next, a, b))
  71722. return true;
  71723. p = p.next;
  71724. } while (p !== a);
  71725. return false;
  71726. }
  71727. // check if a polygon diagonal is locally inside the polygon
  71728. function locallyInside(a, b) {
  71729. return area(a.prev, a, a.next) < 0
  71730. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71731. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71732. }
  71733. // check if the middle point of a polygon diagonal is inside the polygon
  71734. function middleInside(a, b) {
  71735. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71736. do {
  71737. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71738. inside = !inside;
  71739. p = p.next;
  71740. } while (p !== a);
  71741. return inside;
  71742. }
  71743. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71744. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71745. function splitPolygon(a, b) {
  71746. 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;
  71747. a.next = b;
  71748. b.prev = a;
  71749. a2.next = an;
  71750. an.prev = a2;
  71751. b2.next = a2;
  71752. a2.prev = b2;
  71753. bp.next = b2;
  71754. b2.prev = bp;
  71755. return b2;
  71756. }
  71757. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71758. function insertNode(i, x, y, last) {
  71759. var p = new Node(i, x, y);
  71760. if (!last) {
  71761. p.prev = p;
  71762. p.next = p;
  71763. }
  71764. else {
  71765. p.next = last.next;
  71766. p.prev = last;
  71767. last.next.prev = p;
  71768. last.next = p;
  71769. }
  71770. return p;
  71771. }
  71772. function removeNode(p) {
  71773. p.next.prev = p.prev;
  71774. p.prev.next = p.next;
  71775. if (p.prevZ)
  71776. p.prevZ.nextZ = p.nextZ;
  71777. if (p.nextZ)
  71778. p.nextZ.prevZ = p.prevZ;
  71779. }
  71780. /**
  71781. * return a percentage difference between the polygon area and its triangulation area;
  71782. * used to verify correctness of triangulation
  71783. */
  71784. function deviation(data, holeIndices, dim, triangles) {
  71785. var hasHoles = holeIndices && holeIndices.length;
  71786. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71787. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71788. if (hasHoles) {
  71789. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71790. var start = holeIndices[i] * dim;
  71791. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71792. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71793. }
  71794. }
  71795. var trianglesArea = 0;
  71796. for (i = 0; i < triangles.length; i += 3) {
  71797. var a = triangles[i] * dim;
  71798. var b = triangles[i + 1] * dim;
  71799. var c = triangles[i + 2] * dim;
  71800. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71801. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71802. }
  71803. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71804. }
  71805. Earcut.deviation = deviation;
  71806. ;
  71807. function signedArea(data, start, end, dim) {
  71808. var sum = 0;
  71809. for (var i = start, j = end - dim; i < end; i += dim) {
  71810. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71811. j = i;
  71812. }
  71813. return sum;
  71814. }
  71815. /**
  71816. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71817. */
  71818. function flatten(data) {
  71819. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71820. for (var i = 0; i < data.length; i++) {
  71821. for (var j = 0; j < data[i].length; j++) {
  71822. for (var d = 0; d < dim; d++)
  71823. result.vertices.push(data[i][j][d]);
  71824. }
  71825. if (i > 0) {
  71826. holeIndex += data[i - 1].length;
  71827. result.holes.push(holeIndex);
  71828. }
  71829. }
  71830. return result;
  71831. }
  71832. Earcut.flatten = flatten;
  71833. ;
  71834. })(Earcut || (Earcut = {}));
  71835. //# sourceMappingURL=babylon.earcut.js.map
  71836. var BABYLON;
  71837. (function (BABYLON) {
  71838. var IndexedVector2 = /** @class */ (function (_super) {
  71839. __extends(IndexedVector2, _super);
  71840. function IndexedVector2(original, index) {
  71841. var _this = _super.call(this, original.x, original.y) || this;
  71842. _this.index = index;
  71843. return _this;
  71844. }
  71845. return IndexedVector2;
  71846. }(BABYLON.Vector2));
  71847. var PolygonPoints = /** @class */ (function () {
  71848. function PolygonPoints() {
  71849. this.elements = new Array();
  71850. }
  71851. PolygonPoints.prototype.add = function (originalPoints) {
  71852. var _this = this;
  71853. var result = new Array();
  71854. originalPoints.forEach(function (point) {
  71855. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71856. var newPoint = new IndexedVector2(point, _this.elements.length);
  71857. result.push(newPoint);
  71858. _this.elements.push(newPoint);
  71859. }
  71860. });
  71861. return result;
  71862. };
  71863. PolygonPoints.prototype.computeBounds = function () {
  71864. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71865. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71866. this.elements.forEach(function (point) {
  71867. // x
  71868. if (point.x < lmin.x) {
  71869. lmin.x = point.x;
  71870. }
  71871. else if (point.x > lmax.x) {
  71872. lmax.x = point.x;
  71873. }
  71874. // y
  71875. if (point.y < lmin.y) {
  71876. lmin.y = point.y;
  71877. }
  71878. else if (point.y > lmax.y) {
  71879. lmax.y = point.y;
  71880. }
  71881. });
  71882. return {
  71883. min: lmin,
  71884. max: lmax,
  71885. width: lmax.x - lmin.x,
  71886. height: lmax.y - lmin.y
  71887. };
  71888. };
  71889. return PolygonPoints;
  71890. }());
  71891. var Polygon = /** @class */ (function () {
  71892. function Polygon() {
  71893. }
  71894. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  71895. return [
  71896. new BABYLON.Vector2(xmin, ymin),
  71897. new BABYLON.Vector2(xmax, ymin),
  71898. new BABYLON.Vector2(xmax, ymax),
  71899. new BABYLON.Vector2(xmin, ymax)
  71900. ];
  71901. };
  71902. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  71903. if (cx === void 0) { cx = 0; }
  71904. if (cy === void 0) { cy = 0; }
  71905. if (numberOfSides === void 0) { numberOfSides = 32; }
  71906. var result = new Array();
  71907. var angle = 0;
  71908. var increment = (Math.PI * 2) / numberOfSides;
  71909. for (var i = 0; i < numberOfSides; i++) {
  71910. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  71911. angle -= increment;
  71912. }
  71913. return result;
  71914. };
  71915. Polygon.Parse = function (input) {
  71916. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  71917. var i, result = [];
  71918. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  71919. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  71920. }
  71921. return result;
  71922. };
  71923. Polygon.StartingAt = function (x, y) {
  71924. return BABYLON.Path2.StartingAt(x, y);
  71925. };
  71926. return Polygon;
  71927. }());
  71928. BABYLON.Polygon = Polygon;
  71929. var PolygonMeshBuilder = /** @class */ (function () {
  71930. function PolygonMeshBuilder(name, contours, scene) {
  71931. this._points = new PolygonPoints();
  71932. this._outlinepoints = new PolygonPoints();
  71933. this._holes = new Array();
  71934. this._epoints = new Array();
  71935. this._eholes = new Array();
  71936. this._name = name;
  71937. this._scene = scene;
  71938. var points;
  71939. if (contours instanceof BABYLON.Path2) {
  71940. points = contours.getPoints();
  71941. }
  71942. else {
  71943. points = contours;
  71944. }
  71945. this._addToepoint(points);
  71946. this._points.add(points);
  71947. this._outlinepoints.add(points);
  71948. }
  71949. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  71950. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  71951. var p = points_1[_i];
  71952. this._epoints.push(p.x, p.y);
  71953. }
  71954. };
  71955. PolygonMeshBuilder.prototype.addHole = function (hole) {
  71956. this._points.add(hole);
  71957. var holepoints = new PolygonPoints();
  71958. holepoints.add(hole);
  71959. this._holes.push(holepoints);
  71960. this._eholes.push(this._epoints.length / 2);
  71961. this._addToepoint(hole);
  71962. return this;
  71963. };
  71964. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  71965. var _this = this;
  71966. if (updatable === void 0) { updatable = false; }
  71967. if (depth === void 0) { depth = 0; }
  71968. var result = new BABYLON.Mesh(this._name, this._scene);
  71969. var normals = new Array();
  71970. var positions = new Array();
  71971. var uvs = new Array();
  71972. var bounds = this._points.computeBounds();
  71973. this._points.elements.forEach(function (p) {
  71974. normals.push(0, 1.0, 0);
  71975. positions.push(p.x, 0, p.y);
  71976. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  71977. });
  71978. var indices = new Array();
  71979. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  71980. for (var i = 0; i < res.length; i++) {
  71981. indices.push(res[i]);
  71982. }
  71983. if (depth > 0) {
  71984. var positionscount = (positions.length / 3); //get the current pointcount
  71985. this._points.elements.forEach(function (p) {
  71986. normals.push(0, -1.0, 0);
  71987. positions.push(p.x, -depth, p.y);
  71988. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  71989. });
  71990. var totalCount = indices.length;
  71991. for (var i = 0; i < totalCount; i += 3) {
  71992. var i0 = indices[i + 0];
  71993. var i1 = indices[i + 1];
  71994. var i2 = indices[i + 2];
  71995. indices.push(i2 + positionscount);
  71996. indices.push(i1 + positionscount);
  71997. indices.push(i0 + positionscount);
  71998. }
  71999. //Add the sides
  72000. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72001. this._holes.forEach(function (hole) {
  72002. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72003. });
  72004. }
  72005. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72006. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72007. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72008. result.setIndices(indices);
  72009. return result;
  72010. };
  72011. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72012. var StartIndex = positions.length / 3;
  72013. var ulength = 0;
  72014. for (var i = 0; i < points.elements.length; i++) {
  72015. var p = points.elements[i];
  72016. var p1;
  72017. if ((i + 1) > points.elements.length - 1) {
  72018. p1 = points.elements[0];
  72019. }
  72020. else {
  72021. p1 = points.elements[i + 1];
  72022. }
  72023. positions.push(p.x, 0, p.y);
  72024. positions.push(p.x, -depth, p.y);
  72025. positions.push(p1.x, 0, p1.y);
  72026. positions.push(p1.x, -depth, p1.y);
  72027. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72028. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72029. var v3 = v2.subtract(v1);
  72030. var v4 = new BABYLON.Vector3(0, 1, 0);
  72031. var vn = BABYLON.Vector3.Cross(v3, v4);
  72032. vn = vn.normalize();
  72033. uvs.push(ulength / bounds.width, 0);
  72034. uvs.push(ulength / bounds.width, 1);
  72035. ulength += v3.length();
  72036. uvs.push((ulength / bounds.width), 0);
  72037. uvs.push((ulength / bounds.width), 1);
  72038. if (!flip) {
  72039. normals.push(-vn.x, -vn.y, -vn.z);
  72040. normals.push(-vn.x, -vn.y, -vn.z);
  72041. normals.push(-vn.x, -vn.y, -vn.z);
  72042. normals.push(-vn.x, -vn.y, -vn.z);
  72043. indices.push(StartIndex);
  72044. indices.push(StartIndex + 1);
  72045. indices.push(StartIndex + 2);
  72046. indices.push(StartIndex + 1);
  72047. indices.push(StartIndex + 3);
  72048. indices.push(StartIndex + 2);
  72049. }
  72050. else {
  72051. normals.push(vn.x, vn.y, vn.z);
  72052. normals.push(vn.x, vn.y, vn.z);
  72053. normals.push(vn.x, vn.y, vn.z);
  72054. normals.push(vn.x, vn.y, vn.z);
  72055. indices.push(StartIndex);
  72056. indices.push(StartIndex + 2);
  72057. indices.push(StartIndex + 1);
  72058. indices.push(StartIndex + 1);
  72059. indices.push(StartIndex + 2);
  72060. indices.push(StartIndex + 3);
  72061. }
  72062. StartIndex += 4;
  72063. }
  72064. ;
  72065. };
  72066. return PolygonMeshBuilder;
  72067. }());
  72068. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72069. })(BABYLON || (BABYLON = {}));
  72070. //# sourceMappingURL=babylon.polygonMesh.js.map
  72071. var BABYLON;
  72072. (function (BABYLON) {
  72073. // Unique ID when we import meshes from Babylon to CSG
  72074. var currentCSGMeshId = 0;
  72075. // # class Vertex
  72076. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72077. // one to provide additional features like texture coordinates and vertex
  72078. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72079. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72080. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72081. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72082. // is not used anywhere else.
  72083. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72084. var Vertex = /** @class */ (function () {
  72085. function Vertex(pos, normal, uv) {
  72086. this.pos = pos;
  72087. this.normal = normal;
  72088. this.uv = uv;
  72089. }
  72090. Vertex.prototype.clone = function () {
  72091. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72092. };
  72093. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72094. // orientation of a polygon is flipped.
  72095. Vertex.prototype.flip = function () {
  72096. this.normal = this.normal.scale(-1);
  72097. };
  72098. // Create a new vertex between this vertex and `other` by linearly
  72099. // interpolating all properties using a parameter of `t`. Subclasses should
  72100. // override this to interpolate additional properties.
  72101. Vertex.prototype.interpolate = function (other, t) {
  72102. 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));
  72103. };
  72104. return Vertex;
  72105. }());
  72106. // # class Plane
  72107. // Represents a plane in 3D space.
  72108. var Plane = /** @class */ (function () {
  72109. function Plane(normal, w) {
  72110. this.normal = normal;
  72111. this.w = w;
  72112. }
  72113. Plane.FromPoints = function (a, b, c) {
  72114. var v0 = c.subtract(a);
  72115. var v1 = b.subtract(a);
  72116. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72117. return null;
  72118. }
  72119. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72120. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72121. };
  72122. Plane.prototype.clone = function () {
  72123. return new Plane(this.normal.clone(), this.w);
  72124. };
  72125. Plane.prototype.flip = function () {
  72126. this.normal.scaleInPlace(-1);
  72127. this.w = -this.w;
  72128. };
  72129. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72130. // fragments in the appropriate lists. Coplanar polygons go into either
  72131. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72132. // respect to this plane. Polygons in front or in back of this plane go into
  72133. // either `front` or `back`.
  72134. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72135. var COPLANAR = 0;
  72136. var FRONT = 1;
  72137. var BACK = 2;
  72138. var SPANNING = 3;
  72139. // Classify each point as well as the entire polygon into one of the above
  72140. // four classes.
  72141. var polygonType = 0;
  72142. var types = [];
  72143. var i;
  72144. var t;
  72145. for (i = 0; i < polygon.vertices.length; i++) {
  72146. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72147. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72148. polygonType |= type;
  72149. types.push(type);
  72150. }
  72151. // Put the polygon in the correct list, splitting it when necessary.
  72152. switch (polygonType) {
  72153. case COPLANAR:
  72154. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72155. break;
  72156. case FRONT:
  72157. front.push(polygon);
  72158. break;
  72159. case BACK:
  72160. back.push(polygon);
  72161. break;
  72162. case SPANNING:
  72163. var f = [], b = [];
  72164. for (i = 0; i < polygon.vertices.length; i++) {
  72165. var j = (i + 1) % polygon.vertices.length;
  72166. var ti = types[i], tj = types[j];
  72167. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72168. if (ti !== BACK)
  72169. f.push(vi);
  72170. if (ti !== FRONT)
  72171. b.push(ti !== BACK ? vi.clone() : vi);
  72172. if ((ti | tj) === SPANNING) {
  72173. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72174. var v = vi.interpolate(vj, t);
  72175. f.push(v);
  72176. b.push(v.clone());
  72177. }
  72178. }
  72179. var poly;
  72180. if (f.length >= 3) {
  72181. poly = new Polygon(f, polygon.shared);
  72182. if (poly.plane)
  72183. front.push(poly);
  72184. }
  72185. if (b.length >= 3) {
  72186. poly = new Polygon(b, polygon.shared);
  72187. if (poly.plane)
  72188. back.push(poly);
  72189. }
  72190. break;
  72191. }
  72192. };
  72193. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72194. // point is on the plane.
  72195. Plane.EPSILON = 1e-5;
  72196. return Plane;
  72197. }());
  72198. // # class Polygon
  72199. // Represents a convex polygon. The vertices used to initialize a polygon must
  72200. // be coplanar and form a convex loop.
  72201. //
  72202. // Each convex polygon has a `shared` property, which is shared between all
  72203. // polygons that are clones of each other or were split from the same polygon.
  72204. // This can be used to define per-polygon properties (such as surface color).
  72205. var Polygon = /** @class */ (function () {
  72206. function Polygon(vertices, shared) {
  72207. this.vertices = vertices;
  72208. this.shared = shared;
  72209. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72210. }
  72211. Polygon.prototype.clone = function () {
  72212. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72213. return new Polygon(vertices, this.shared);
  72214. };
  72215. Polygon.prototype.flip = function () {
  72216. this.vertices.reverse().map(function (v) { v.flip(); });
  72217. this.plane.flip();
  72218. };
  72219. return Polygon;
  72220. }());
  72221. // # class Node
  72222. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72223. // by picking a polygon to split along. That polygon (and all other coplanar
  72224. // polygons) are added directly to that node and the other polygons are added to
  72225. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72226. // no distinction between internal and leaf nodes.
  72227. var Node = /** @class */ (function () {
  72228. function Node(polygons) {
  72229. this.plane = null;
  72230. this.front = null;
  72231. this.back = null;
  72232. this.polygons = new Array();
  72233. if (polygons) {
  72234. this.build(polygons);
  72235. }
  72236. }
  72237. Node.prototype.clone = function () {
  72238. var node = new Node();
  72239. node.plane = this.plane && this.plane.clone();
  72240. node.front = this.front && this.front.clone();
  72241. node.back = this.back && this.back.clone();
  72242. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72243. return node;
  72244. };
  72245. // Convert solid space to empty space and empty space to solid space.
  72246. Node.prototype.invert = function () {
  72247. for (var i = 0; i < this.polygons.length; i++) {
  72248. this.polygons[i].flip();
  72249. }
  72250. if (this.plane) {
  72251. this.plane.flip();
  72252. }
  72253. if (this.front) {
  72254. this.front.invert();
  72255. }
  72256. if (this.back) {
  72257. this.back.invert();
  72258. }
  72259. var temp = this.front;
  72260. this.front = this.back;
  72261. this.back = temp;
  72262. };
  72263. // Recursively remove all polygons in `polygons` that are inside this BSP
  72264. // tree.
  72265. Node.prototype.clipPolygons = function (polygons) {
  72266. if (!this.plane)
  72267. return polygons.slice();
  72268. var front = new Array(), back = new Array();
  72269. for (var i = 0; i < polygons.length; i++) {
  72270. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72271. }
  72272. if (this.front) {
  72273. front = this.front.clipPolygons(front);
  72274. }
  72275. if (this.back) {
  72276. back = this.back.clipPolygons(back);
  72277. }
  72278. else {
  72279. back = [];
  72280. }
  72281. return front.concat(back);
  72282. };
  72283. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72284. // `bsp`.
  72285. Node.prototype.clipTo = function (bsp) {
  72286. this.polygons = bsp.clipPolygons(this.polygons);
  72287. if (this.front)
  72288. this.front.clipTo(bsp);
  72289. if (this.back)
  72290. this.back.clipTo(bsp);
  72291. };
  72292. // Return a list of all polygons in this BSP tree.
  72293. Node.prototype.allPolygons = function () {
  72294. var polygons = this.polygons.slice();
  72295. if (this.front)
  72296. polygons = polygons.concat(this.front.allPolygons());
  72297. if (this.back)
  72298. polygons = polygons.concat(this.back.allPolygons());
  72299. return polygons;
  72300. };
  72301. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72302. // new polygons are filtered down to the bottom of the tree and become new
  72303. // nodes there. Each set of polygons is partitioned using the first polygon
  72304. // (no heuristic is used to pick a good split).
  72305. Node.prototype.build = function (polygons) {
  72306. if (!polygons.length)
  72307. return;
  72308. if (!this.plane)
  72309. this.plane = polygons[0].plane.clone();
  72310. var front = new Array(), back = new Array();
  72311. for (var i = 0; i < polygons.length; i++) {
  72312. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72313. }
  72314. if (front.length) {
  72315. if (!this.front)
  72316. this.front = new Node();
  72317. this.front.build(front);
  72318. }
  72319. if (back.length) {
  72320. if (!this.back)
  72321. this.back = new Node();
  72322. this.back.build(back);
  72323. }
  72324. };
  72325. return Node;
  72326. }());
  72327. var CSG = /** @class */ (function () {
  72328. function CSG() {
  72329. this.polygons = new Array();
  72330. }
  72331. // Convert BABYLON.Mesh to BABYLON.CSG
  72332. CSG.FromMesh = function (mesh) {
  72333. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72334. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72335. if (mesh instanceof BABYLON.Mesh) {
  72336. mesh.computeWorldMatrix(true);
  72337. matrix = mesh.getWorldMatrix();
  72338. meshPosition = mesh.position.clone();
  72339. meshRotation = mesh.rotation.clone();
  72340. if (mesh.rotationQuaternion) {
  72341. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72342. }
  72343. meshScaling = mesh.scaling.clone();
  72344. }
  72345. else {
  72346. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72347. }
  72348. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72349. var subMeshes = mesh.subMeshes;
  72350. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72351. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72352. vertices = [];
  72353. for (var j = 0; j < 3; j++) {
  72354. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72355. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72356. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72357. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72358. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72359. vertex = new Vertex(position, normal, uv);
  72360. vertices.push(vertex);
  72361. }
  72362. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72363. // To handle the case of degenerated triangle
  72364. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72365. if (polygon.plane)
  72366. polygons.push(polygon);
  72367. }
  72368. }
  72369. var csg = CSG.FromPolygons(polygons);
  72370. csg.matrix = matrix;
  72371. csg.position = meshPosition;
  72372. csg.rotation = meshRotation;
  72373. csg.scaling = meshScaling;
  72374. csg.rotationQuaternion = meshRotationQuaternion;
  72375. currentCSGMeshId++;
  72376. return csg;
  72377. };
  72378. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72379. CSG.FromPolygons = function (polygons) {
  72380. var csg = new CSG();
  72381. csg.polygons = polygons;
  72382. return csg;
  72383. };
  72384. CSG.prototype.clone = function () {
  72385. var csg = new CSG();
  72386. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72387. csg.copyTransformAttributes(this);
  72388. return csg;
  72389. };
  72390. CSG.prototype.union = function (csg) {
  72391. var a = new Node(this.clone().polygons);
  72392. var b = new Node(csg.clone().polygons);
  72393. a.clipTo(b);
  72394. b.clipTo(a);
  72395. b.invert();
  72396. b.clipTo(a);
  72397. b.invert();
  72398. a.build(b.allPolygons());
  72399. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72400. };
  72401. CSG.prototype.unionInPlace = function (csg) {
  72402. var a = new Node(this.polygons);
  72403. var b = new Node(csg.polygons);
  72404. a.clipTo(b);
  72405. b.clipTo(a);
  72406. b.invert();
  72407. b.clipTo(a);
  72408. b.invert();
  72409. a.build(b.allPolygons());
  72410. this.polygons = a.allPolygons();
  72411. };
  72412. CSG.prototype.subtract = function (csg) {
  72413. var a = new Node(this.clone().polygons);
  72414. var b = new Node(csg.clone().polygons);
  72415. a.invert();
  72416. a.clipTo(b);
  72417. b.clipTo(a);
  72418. b.invert();
  72419. b.clipTo(a);
  72420. b.invert();
  72421. a.build(b.allPolygons());
  72422. a.invert();
  72423. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72424. };
  72425. CSG.prototype.subtractInPlace = function (csg) {
  72426. var a = new Node(this.polygons);
  72427. var b = new Node(csg.polygons);
  72428. a.invert();
  72429. a.clipTo(b);
  72430. b.clipTo(a);
  72431. b.invert();
  72432. b.clipTo(a);
  72433. b.invert();
  72434. a.build(b.allPolygons());
  72435. a.invert();
  72436. this.polygons = a.allPolygons();
  72437. };
  72438. CSG.prototype.intersect = function (csg) {
  72439. var a = new Node(this.clone().polygons);
  72440. var b = new Node(csg.clone().polygons);
  72441. a.invert();
  72442. b.clipTo(a);
  72443. b.invert();
  72444. a.clipTo(b);
  72445. b.clipTo(a);
  72446. a.build(b.allPolygons());
  72447. a.invert();
  72448. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72449. };
  72450. CSG.prototype.intersectInPlace = function (csg) {
  72451. var a = new Node(this.polygons);
  72452. var b = new Node(csg.polygons);
  72453. a.invert();
  72454. b.clipTo(a);
  72455. b.invert();
  72456. a.clipTo(b);
  72457. b.clipTo(a);
  72458. a.build(b.allPolygons());
  72459. a.invert();
  72460. this.polygons = a.allPolygons();
  72461. };
  72462. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72463. // not modified.
  72464. CSG.prototype.inverse = function () {
  72465. var csg = this.clone();
  72466. csg.inverseInPlace();
  72467. return csg;
  72468. };
  72469. CSG.prototype.inverseInPlace = function () {
  72470. this.polygons.map(function (p) { p.flip(); });
  72471. };
  72472. // This is used to keep meshes transformations so they can be restored
  72473. // when we build back a Babylon Mesh
  72474. // NB : All CSG operations are performed in world coordinates
  72475. CSG.prototype.copyTransformAttributes = function (csg) {
  72476. this.matrix = csg.matrix;
  72477. this.position = csg.position;
  72478. this.rotation = csg.rotation;
  72479. this.scaling = csg.scaling;
  72480. this.rotationQuaternion = csg.rotationQuaternion;
  72481. return this;
  72482. };
  72483. // Build Raw mesh from CSG
  72484. // Coordinates here are in world space
  72485. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72486. var matrix = this.matrix.clone();
  72487. matrix.invert();
  72488. 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;
  72489. if (keepSubMeshes) {
  72490. // Sort Polygons, since subMeshes are indices range
  72491. polygons.sort(function (a, b) {
  72492. if (a.shared.meshId === b.shared.meshId) {
  72493. return a.shared.subMeshId - b.shared.subMeshId;
  72494. }
  72495. else {
  72496. return a.shared.meshId - b.shared.meshId;
  72497. }
  72498. });
  72499. }
  72500. for (var i = 0, il = polygons.length; i < il; i++) {
  72501. polygon = polygons[i];
  72502. // Building SubMeshes
  72503. if (!subMesh_dict[polygon.shared.meshId]) {
  72504. subMesh_dict[polygon.shared.meshId] = {};
  72505. }
  72506. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72507. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72508. indexStart: +Infinity,
  72509. indexEnd: -Infinity,
  72510. materialIndex: polygon.shared.materialIndex
  72511. };
  72512. }
  72513. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72514. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72515. polygonIndices[0] = 0;
  72516. polygonIndices[1] = j - 1;
  72517. polygonIndices[2] = j;
  72518. for (var k = 0; k < 3; k++) {
  72519. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72520. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72521. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72522. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72523. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72524. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72525. // Check if 2 points can be merged
  72526. if (!(typeof vertex_idx !== 'undefined' &&
  72527. normals[vertex_idx * 3] === localNormal.x &&
  72528. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72529. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72530. uvs[vertex_idx * 2] === uv.x &&
  72531. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72532. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72533. uvs.push(uv.x, uv.y);
  72534. normals.push(normal.x, normal.y, normal.z);
  72535. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72536. }
  72537. indices.push(vertex_idx);
  72538. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72539. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72540. currentIndex++;
  72541. }
  72542. }
  72543. }
  72544. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72545. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72546. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72547. mesh.setIndices(indices, null);
  72548. if (keepSubMeshes) {
  72549. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72550. var materialIndexOffset = 0, materialMaxIndex;
  72551. mesh.subMeshes = new Array();
  72552. for (var m in subMesh_dict) {
  72553. materialMaxIndex = -1;
  72554. for (var sm in subMesh_dict[m]) {
  72555. subMesh_obj = subMesh_dict[m][sm];
  72556. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72557. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72558. }
  72559. materialIndexOffset += ++materialMaxIndex;
  72560. }
  72561. }
  72562. return mesh;
  72563. };
  72564. // Build Mesh from CSG taking material and transforms into account
  72565. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72566. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72567. mesh.material = material;
  72568. mesh.position.copyFrom(this.position);
  72569. mesh.rotation.copyFrom(this.rotation);
  72570. if (this.rotationQuaternion) {
  72571. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72572. }
  72573. mesh.scaling.copyFrom(this.scaling);
  72574. mesh.computeWorldMatrix(true);
  72575. return mesh;
  72576. };
  72577. return CSG;
  72578. }());
  72579. BABYLON.CSG = CSG;
  72580. })(BABYLON || (BABYLON = {}));
  72581. //# sourceMappingURL=babylon.csg.js.map
  72582. var BABYLON;
  72583. (function (BABYLON) {
  72584. var LensFlare = /** @class */ (function () {
  72585. function LensFlare(size, position, color, imgUrl, system) {
  72586. this.size = size;
  72587. this.position = position;
  72588. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72589. this.color = color || new BABYLON.Color3(1, 1, 1);
  72590. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72591. this._system = system;
  72592. system.lensFlares.push(this);
  72593. }
  72594. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72595. return new LensFlare(size, position, color, imgUrl, system);
  72596. };
  72597. LensFlare.prototype.dispose = function () {
  72598. if (this.texture) {
  72599. this.texture.dispose();
  72600. }
  72601. // Remove from scene
  72602. var index = this._system.lensFlares.indexOf(this);
  72603. this._system.lensFlares.splice(index, 1);
  72604. };
  72605. ;
  72606. return LensFlare;
  72607. }());
  72608. BABYLON.LensFlare = LensFlare;
  72609. })(BABYLON || (BABYLON = {}));
  72610. //# sourceMappingURL=babylon.lensFlare.js.map
  72611. var BABYLON;
  72612. (function (BABYLON) {
  72613. var LensFlareSystem = /** @class */ (function () {
  72614. function LensFlareSystem(name, emitter, scene) {
  72615. this.name = name;
  72616. this.lensFlares = new Array();
  72617. this.borderLimit = 300;
  72618. this.viewportBorder = 0;
  72619. this.layerMask = 0x0FFFFFFF;
  72620. this._vertexBuffers = {};
  72621. this._isEnabled = true;
  72622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72623. this._emitter = emitter;
  72624. this.id = name;
  72625. scene.lensFlareSystems.push(this);
  72626. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72627. var engine = scene.getEngine();
  72628. // VBO
  72629. var vertices = [];
  72630. vertices.push(1, 1);
  72631. vertices.push(-1, 1);
  72632. vertices.push(-1, -1);
  72633. vertices.push(1, -1);
  72634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72635. // Indices
  72636. var indices = [];
  72637. indices.push(0);
  72638. indices.push(1);
  72639. indices.push(2);
  72640. indices.push(0);
  72641. indices.push(2);
  72642. indices.push(3);
  72643. this._indexBuffer = engine.createIndexBuffer(indices);
  72644. // Effects
  72645. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72646. }
  72647. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72648. get: function () {
  72649. return this._isEnabled;
  72650. },
  72651. set: function (value) {
  72652. this._isEnabled = value;
  72653. },
  72654. enumerable: true,
  72655. configurable: true
  72656. });
  72657. LensFlareSystem.prototype.getScene = function () {
  72658. return this._scene;
  72659. };
  72660. LensFlareSystem.prototype.getEmitter = function () {
  72661. return this._emitter;
  72662. };
  72663. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72664. this._emitter = newEmitter;
  72665. };
  72666. LensFlareSystem.prototype.getEmitterPosition = function () {
  72667. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72668. };
  72669. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72670. var position = this.getEmitterPosition();
  72671. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72672. this._positionX = position.x;
  72673. this._positionY = position.y;
  72674. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72675. if (this.viewportBorder > 0) {
  72676. globalViewport.x -= this.viewportBorder;
  72677. globalViewport.y -= this.viewportBorder;
  72678. globalViewport.width += this.viewportBorder * 2;
  72679. globalViewport.height += this.viewportBorder * 2;
  72680. position.x += this.viewportBorder;
  72681. position.y += this.viewportBorder;
  72682. this._positionX += this.viewportBorder;
  72683. this._positionY += this.viewportBorder;
  72684. }
  72685. if (position.z > 0) {
  72686. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72687. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72688. return true;
  72689. }
  72690. return true;
  72691. }
  72692. return false;
  72693. };
  72694. LensFlareSystem.prototype._isVisible = function () {
  72695. if (!this._isEnabled || !this._scene.activeCamera) {
  72696. return false;
  72697. }
  72698. var emitterPosition = this.getEmitterPosition();
  72699. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72700. var distance = direction.length();
  72701. direction.normalize();
  72702. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72703. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72704. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72705. };
  72706. LensFlareSystem.prototype.render = function () {
  72707. if (!this._effect.isReady() || !this._scene.activeCamera)
  72708. return false;
  72709. var engine = this._scene.getEngine();
  72710. var viewport = this._scene.activeCamera.viewport;
  72711. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72712. // Position
  72713. if (!this.computeEffectivePosition(globalViewport)) {
  72714. return false;
  72715. }
  72716. // Visibility
  72717. if (!this._isVisible()) {
  72718. return false;
  72719. }
  72720. // Intensity
  72721. var awayX;
  72722. var awayY;
  72723. if (this._positionX < this.borderLimit + globalViewport.x) {
  72724. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72725. }
  72726. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72727. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72728. }
  72729. else {
  72730. awayX = 0;
  72731. }
  72732. if (this._positionY < this.borderLimit + globalViewport.y) {
  72733. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72734. }
  72735. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72736. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72737. }
  72738. else {
  72739. awayY = 0;
  72740. }
  72741. var away = (awayX > awayY) ? awayX : awayY;
  72742. away -= this.viewportBorder;
  72743. if (away > this.borderLimit) {
  72744. away = this.borderLimit;
  72745. }
  72746. var intensity = 1.0 - (away / this.borderLimit);
  72747. if (intensity < 0) {
  72748. return false;
  72749. }
  72750. if (intensity > 1.0) {
  72751. intensity = 1.0;
  72752. }
  72753. if (this.viewportBorder > 0) {
  72754. globalViewport.x += this.viewportBorder;
  72755. globalViewport.y += this.viewportBorder;
  72756. globalViewport.width -= this.viewportBorder * 2;
  72757. globalViewport.height -= this.viewportBorder * 2;
  72758. this._positionX -= this.viewportBorder;
  72759. this._positionY -= this.viewportBorder;
  72760. }
  72761. // Position
  72762. var centerX = globalViewport.x + globalViewport.width / 2;
  72763. var centerY = globalViewport.y + globalViewport.height / 2;
  72764. var distX = centerX - this._positionX;
  72765. var distY = centerY - this._positionY;
  72766. // Effects
  72767. engine.enableEffect(this._effect);
  72768. engine.setState(false);
  72769. engine.setDepthBuffer(false);
  72770. // VBOs
  72771. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72772. // Flares
  72773. for (var index = 0; index < this.lensFlares.length; index++) {
  72774. var flare = this.lensFlares[index];
  72775. engine.setAlphaMode(flare.alphaMode);
  72776. var x = centerX - (distX * flare.position);
  72777. var y = centerY - (distY * flare.position);
  72778. var cw = flare.size;
  72779. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72780. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72781. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72782. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72783. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72784. // Texture
  72785. this._effect.setTexture("textureSampler", flare.texture);
  72786. // Color
  72787. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72788. // Draw order
  72789. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72790. }
  72791. engine.setDepthBuffer(true);
  72792. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72793. return true;
  72794. };
  72795. LensFlareSystem.prototype.dispose = function () {
  72796. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72797. if (vertexBuffer) {
  72798. vertexBuffer.dispose();
  72799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72800. }
  72801. if (this._indexBuffer) {
  72802. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72803. this._indexBuffer = null;
  72804. }
  72805. while (this.lensFlares.length) {
  72806. this.lensFlares[0].dispose();
  72807. }
  72808. // Remove from scene
  72809. var index = this._scene.lensFlareSystems.indexOf(this);
  72810. this._scene.lensFlareSystems.splice(index, 1);
  72811. };
  72812. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72813. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72814. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72815. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72816. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72817. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72818. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72819. var parsedFlare = parsedLensFlareSystem.flares[index];
  72820. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72821. }
  72822. return lensFlareSystem;
  72823. };
  72824. LensFlareSystem.prototype.serialize = function () {
  72825. var serializationObject = {};
  72826. serializationObject.id = this.id;
  72827. serializationObject.name = this.name;
  72828. serializationObject.emitterId = this.getEmitter().id;
  72829. serializationObject.borderLimit = this.borderLimit;
  72830. serializationObject.flares = [];
  72831. for (var index = 0; index < this.lensFlares.length; index++) {
  72832. var flare = this.lensFlares[index];
  72833. serializationObject.flares.push({
  72834. size: flare.size,
  72835. position: flare.position,
  72836. color: flare.color.asArray(),
  72837. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72838. });
  72839. }
  72840. return serializationObject;
  72841. };
  72842. return LensFlareSystem;
  72843. }());
  72844. BABYLON.LensFlareSystem = LensFlareSystem;
  72845. })(BABYLON || (BABYLON = {}));
  72846. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. /**
  72850. * This is a holder class for the physics joint created by the physics plugin.
  72851. * It holds a set of functions to control the underlying joint.
  72852. */
  72853. var PhysicsJoint = /** @class */ (function () {
  72854. function PhysicsJoint(type, jointData) {
  72855. this.type = type;
  72856. this.jointData = jointData;
  72857. jointData.nativeParams = jointData.nativeParams || {};
  72858. }
  72859. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72860. get: function () {
  72861. return this._physicsJoint;
  72862. },
  72863. set: function (newJoint) {
  72864. if (this._physicsJoint) {
  72865. //remove from the wolrd
  72866. }
  72867. this._physicsJoint = newJoint;
  72868. },
  72869. enumerable: true,
  72870. configurable: true
  72871. });
  72872. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72873. set: function (physicsPlugin) {
  72874. this._physicsPlugin = physicsPlugin;
  72875. },
  72876. enumerable: true,
  72877. configurable: true
  72878. });
  72879. /**
  72880. * Execute a function that is physics-plugin specific.
  72881. * @param {Function} func the function that will be executed.
  72882. * It accepts two parameters: the physics world and the physics joint.
  72883. */
  72884. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  72885. func(this._physicsPlugin.world, this._physicsJoint);
  72886. };
  72887. //TODO check if the native joints are the same
  72888. //Joint Types
  72889. PhysicsJoint.DistanceJoint = 0;
  72890. PhysicsJoint.HingeJoint = 1;
  72891. PhysicsJoint.BallAndSocketJoint = 2;
  72892. PhysicsJoint.WheelJoint = 3;
  72893. PhysicsJoint.SliderJoint = 4;
  72894. //OIMO
  72895. PhysicsJoint.PrismaticJoint = 5;
  72896. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  72897. PhysicsJoint.UniversalJoint = 6;
  72898. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  72899. //Cannon
  72900. //Similar to a Ball-Joint. Different in params
  72901. PhysicsJoint.PointToPointJoint = 8;
  72902. //Cannon only at the moment
  72903. PhysicsJoint.SpringJoint = 9;
  72904. PhysicsJoint.LockJoint = 10;
  72905. return PhysicsJoint;
  72906. }());
  72907. BABYLON.PhysicsJoint = PhysicsJoint;
  72908. /**
  72909. * A class representing a physics distance joint.
  72910. */
  72911. var DistanceJoint = /** @class */ (function (_super) {
  72912. __extends(DistanceJoint, _super);
  72913. function DistanceJoint(jointData) {
  72914. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  72915. }
  72916. /**
  72917. * Update the predefined distance.
  72918. */
  72919. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  72920. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  72921. };
  72922. return DistanceJoint;
  72923. }(PhysicsJoint));
  72924. BABYLON.DistanceJoint = DistanceJoint;
  72925. var MotorEnabledJoint = /** @class */ (function (_super) {
  72926. __extends(MotorEnabledJoint, _super);
  72927. function MotorEnabledJoint(type, jointData) {
  72928. return _super.call(this, type, jointData) || this;
  72929. }
  72930. /**
  72931. * Set the motor values.
  72932. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72933. * @param {number} force the force to apply
  72934. * @param {number} maxForce max force for this motor.
  72935. */
  72936. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  72937. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72938. };
  72939. /**
  72940. * Set the motor's limits.
  72941. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72942. */
  72943. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72944. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72945. };
  72946. return MotorEnabledJoint;
  72947. }(PhysicsJoint));
  72948. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  72949. /**
  72950. * This class represents a single hinge physics joint
  72951. */
  72952. var HingeJoint = /** @class */ (function (_super) {
  72953. __extends(HingeJoint, _super);
  72954. function HingeJoint(jointData) {
  72955. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  72956. }
  72957. /**
  72958. * Set the motor values.
  72959. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72960. * @param {number} force the force to apply
  72961. * @param {number} maxForce max force for this motor.
  72962. */
  72963. HingeJoint.prototype.setMotor = function (force, maxForce) {
  72964. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72965. };
  72966. /**
  72967. * Set the motor's limits.
  72968. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72969. */
  72970. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72971. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72972. };
  72973. return HingeJoint;
  72974. }(MotorEnabledJoint));
  72975. BABYLON.HingeJoint = HingeJoint;
  72976. /**
  72977. * This class represents a dual hinge physics joint (same as wheel joint)
  72978. */
  72979. var Hinge2Joint = /** @class */ (function (_super) {
  72980. __extends(Hinge2Joint, _super);
  72981. function Hinge2Joint(jointData) {
  72982. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  72983. }
  72984. /**
  72985. * Set the motor values.
  72986. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72987. * @param {number} force the force to apply
  72988. * @param {number} maxForce max force for this motor.
  72989. * @param {motorIndex} the motor's index, 0 or 1.
  72990. */
  72991. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  72992. if (motorIndex === void 0) { motorIndex = 0; }
  72993. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  72994. };
  72995. /**
  72996. * Set the motor limits.
  72997. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72998. * @param {number} upperLimit the upper limit
  72999. * @param {number} lowerLimit lower limit
  73000. * @param {motorIndex} the motor's index, 0 or 1.
  73001. */
  73002. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73003. if (motorIndex === void 0) { motorIndex = 0; }
  73004. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73005. };
  73006. return Hinge2Joint;
  73007. }(MotorEnabledJoint));
  73008. BABYLON.Hinge2Joint = Hinge2Joint;
  73009. })(BABYLON || (BABYLON = {}));
  73010. //# sourceMappingURL=babylon.physicsJoint.js.map
  73011. var BABYLON;
  73012. (function (BABYLON) {
  73013. var PhysicsImpostor = /** @class */ (function () {
  73014. function PhysicsImpostor(object, type, _options, _scene) {
  73015. if (_options === void 0) { _options = { mass: 0 }; }
  73016. var _this = this;
  73017. this.object = object;
  73018. this.type = type;
  73019. this._options = _options;
  73020. this._scene = _scene;
  73021. this._bodyUpdateRequired = false;
  73022. this._onBeforePhysicsStepCallbacks = new Array();
  73023. this._onAfterPhysicsStepCallbacks = new Array();
  73024. this._onPhysicsCollideCallbacks = [];
  73025. this._deltaPosition = BABYLON.Vector3.Zero();
  73026. this._isDisposed = false;
  73027. //temp variables for parent rotation calculations
  73028. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73029. this._tmpQuat = new BABYLON.Quaternion();
  73030. this._tmpQuat2 = new BABYLON.Quaternion();
  73031. /**
  73032. * this function is executed by the physics engine.
  73033. */
  73034. this.beforeStep = function () {
  73035. if (!_this._physicsEngine) {
  73036. return;
  73037. }
  73038. _this.object.translate(_this._deltaPosition, -1);
  73039. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73040. _this.object.computeWorldMatrix(false);
  73041. if (_this.object.parent && _this.object.rotationQuaternion) {
  73042. _this.getParentsRotation();
  73043. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73044. }
  73045. else {
  73046. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73047. }
  73048. if (!_this._options.disableBidirectionalTransformation) {
  73049. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73050. }
  73051. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73052. func(_this);
  73053. });
  73054. };
  73055. /**
  73056. * this function is executed by the physics engine.
  73057. */
  73058. this.afterStep = function () {
  73059. if (!_this._physicsEngine) {
  73060. return;
  73061. }
  73062. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73063. func(_this);
  73064. });
  73065. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73066. // object has now its world rotation. needs to be converted to local.
  73067. if (_this.object.parent && _this.object.rotationQuaternion) {
  73068. _this.getParentsRotation();
  73069. _this._tmpQuat.conjugateInPlace();
  73070. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73071. }
  73072. // take the position set and make it the absolute position of this object.
  73073. _this.object.setAbsolutePosition(_this.object.position);
  73074. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73075. _this.object.translate(_this._deltaPosition, 1);
  73076. };
  73077. /**
  73078. * Legacy collision detection event support
  73079. */
  73080. this.onCollideEvent = null;
  73081. //event and body object due to cannon's event-based architecture.
  73082. this.onCollide = function (e) {
  73083. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73084. return;
  73085. }
  73086. if (!_this._physicsEngine) {
  73087. return;
  73088. }
  73089. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73090. if (otherImpostor) {
  73091. // Legacy collision detection event support
  73092. if (_this.onCollideEvent) {
  73093. _this.onCollideEvent(_this, otherImpostor);
  73094. }
  73095. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73096. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73097. }).forEach(function (obj) {
  73098. obj.callback(_this, otherImpostor);
  73099. });
  73100. }
  73101. };
  73102. //sanity check!
  73103. if (!this.object) {
  73104. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73105. return;
  73106. }
  73107. //legacy support for old syntax.
  73108. if (!this._scene && object.getScene) {
  73109. this._scene = object.getScene();
  73110. }
  73111. if (!this._scene) {
  73112. return;
  73113. }
  73114. this._physicsEngine = this._scene.getPhysicsEngine();
  73115. if (!this._physicsEngine) {
  73116. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73117. }
  73118. else {
  73119. //set the object's quaternion, if not set
  73120. if (!this.object.rotationQuaternion) {
  73121. if (this.object.rotation) {
  73122. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73123. }
  73124. else {
  73125. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73126. }
  73127. }
  73128. //default options params
  73129. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73130. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73131. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73132. this._joints = [];
  73133. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73134. if (!this.object.parent || this._options.ignoreParent) {
  73135. this._init();
  73136. }
  73137. else if (this.object.parent.physicsImpostor) {
  73138. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73139. }
  73140. }
  73141. }
  73142. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73143. get: function () {
  73144. return this._isDisposed;
  73145. },
  73146. enumerable: true,
  73147. configurable: true
  73148. });
  73149. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73150. get: function () {
  73151. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73152. },
  73153. set: function (value) {
  73154. this.setMass(value);
  73155. },
  73156. enumerable: true,
  73157. configurable: true
  73158. });
  73159. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73160. get: function () {
  73161. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73162. },
  73163. set: function (value) {
  73164. if (!this._physicsEngine) {
  73165. return;
  73166. }
  73167. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73168. },
  73169. enumerable: true,
  73170. configurable: true
  73171. });
  73172. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73173. get: function () {
  73174. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73175. },
  73176. set: function (value) {
  73177. if (!this._physicsEngine) {
  73178. return;
  73179. }
  73180. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73181. },
  73182. enumerable: true,
  73183. configurable: true
  73184. });
  73185. /**
  73186. * This function will completly initialize this impostor.
  73187. * It will create a new body - but only if this mesh has no parent.
  73188. * If it has, this impostor will not be used other than to define the impostor
  73189. * of the child mesh.
  73190. */
  73191. PhysicsImpostor.prototype._init = function () {
  73192. if (!this._physicsEngine) {
  73193. return;
  73194. }
  73195. this._physicsEngine.removeImpostor(this);
  73196. this.physicsBody = null;
  73197. this._parent = this._parent || this._getPhysicsParent();
  73198. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73199. this._physicsEngine.addImpostor(this);
  73200. }
  73201. };
  73202. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73203. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73204. var parentMesh = this.object.parent;
  73205. return parentMesh.physicsImpostor;
  73206. }
  73207. return null;
  73208. };
  73209. /**
  73210. * Should a new body be generated.
  73211. */
  73212. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73213. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73214. };
  73215. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73216. this.forceUpdate();
  73217. };
  73218. /**
  73219. * Force a regeneration of this or the parent's impostor's body.
  73220. * Use under cautious - This will remove all joints already implemented.
  73221. */
  73222. PhysicsImpostor.prototype.forceUpdate = function () {
  73223. this._init();
  73224. if (this.parent && !this._options.ignoreParent) {
  73225. this.parent.forceUpdate();
  73226. }
  73227. };
  73228. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73229. /*public get mesh(): AbstractMesh {
  73230. return this._mesh;
  73231. }*/
  73232. /**
  73233. * Gets the body that holds this impostor. Either its own, or its parent.
  73234. */
  73235. get: function () {
  73236. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73237. },
  73238. /**
  73239. * Set the physics body. Used mainly by the physics engine/plugin
  73240. */
  73241. set: function (physicsBody) {
  73242. if (this._physicsBody && this._physicsEngine) {
  73243. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73244. }
  73245. this._physicsBody = physicsBody;
  73246. this.resetUpdateFlags();
  73247. },
  73248. enumerable: true,
  73249. configurable: true
  73250. });
  73251. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73252. get: function () {
  73253. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73254. },
  73255. set: function (value) {
  73256. this._parent = value;
  73257. },
  73258. enumerable: true,
  73259. configurable: true
  73260. });
  73261. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73262. this._bodyUpdateRequired = false;
  73263. };
  73264. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73265. if (this.object.getBoundingInfo) {
  73266. var q = this.object.rotationQuaternion;
  73267. //reset rotation
  73268. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73269. //calculate the world matrix with no rotation
  73270. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73271. var boundingInfo = this.object.getBoundingInfo();
  73272. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73273. //bring back the rotation
  73274. this.object.rotationQuaternion = q;
  73275. //calculate the world matrix with the new rotation
  73276. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73277. return size;
  73278. }
  73279. else {
  73280. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73281. }
  73282. };
  73283. PhysicsImpostor.prototype.getObjectCenter = function () {
  73284. if (this.object.getBoundingInfo) {
  73285. var boundingInfo = this.object.getBoundingInfo();
  73286. return boundingInfo.boundingBox.centerWorld;
  73287. }
  73288. else {
  73289. return this.object.position;
  73290. }
  73291. };
  73292. /**
  73293. * Get a specific parametes from the options parameter.
  73294. */
  73295. PhysicsImpostor.prototype.getParam = function (paramName) {
  73296. return this._options[paramName];
  73297. };
  73298. /**
  73299. * Sets a specific parameter in the options given to the physics plugin
  73300. */
  73301. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73302. this._options[paramName] = value;
  73303. this._bodyUpdateRequired = true;
  73304. };
  73305. /**
  73306. * Specifically change the body's mass option. Won't recreate the physics body object
  73307. */
  73308. PhysicsImpostor.prototype.setMass = function (mass) {
  73309. if (this.getParam("mass") !== mass) {
  73310. this.setParam("mass", mass);
  73311. }
  73312. if (this._physicsEngine) {
  73313. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73314. }
  73315. };
  73316. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73317. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73318. };
  73319. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73320. if (this._physicsEngine) {
  73321. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73322. }
  73323. };
  73324. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73325. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73326. };
  73327. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73328. if (this._physicsEngine) {
  73329. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73330. }
  73331. };
  73332. /**
  73333. * Execute a function with the physics plugin native code.
  73334. * Provide a function the will have two variables - the world object and the physics body object.
  73335. */
  73336. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73337. if (this._physicsEngine) {
  73338. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73339. }
  73340. };
  73341. /**
  73342. * Register a function that will be executed before the physics world is stepping forward.
  73343. */
  73344. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73345. this._onBeforePhysicsStepCallbacks.push(func);
  73346. };
  73347. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73348. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73349. if (index > -1) {
  73350. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73351. }
  73352. else {
  73353. BABYLON.Tools.Warn("Function to remove was not found");
  73354. }
  73355. };
  73356. /**
  73357. * Register a function that will be executed after the physics step
  73358. */
  73359. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73360. this._onAfterPhysicsStepCallbacks.push(func);
  73361. };
  73362. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73363. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73364. if (index > -1) {
  73365. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73366. }
  73367. else {
  73368. BABYLON.Tools.Warn("Function to remove was not found");
  73369. }
  73370. };
  73371. /**
  73372. * register a function that will be executed when this impostor collides against a different body.
  73373. */
  73374. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73375. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73376. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73377. };
  73378. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73379. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73380. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73381. if (index > -1) {
  73382. this._onPhysicsCollideCallbacks.splice(index, 1);
  73383. }
  73384. else {
  73385. BABYLON.Tools.Warn("Function to remove was not found");
  73386. }
  73387. };
  73388. PhysicsImpostor.prototype.getParentsRotation = function () {
  73389. var parent = this.object.parent;
  73390. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73391. while (parent) {
  73392. if (parent.rotationQuaternion) {
  73393. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73394. }
  73395. else {
  73396. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73397. }
  73398. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73399. parent = parent.parent;
  73400. }
  73401. return this._tmpQuat;
  73402. };
  73403. /**
  73404. * Apply a force
  73405. */
  73406. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73407. if (this._physicsEngine) {
  73408. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73409. }
  73410. return this;
  73411. };
  73412. /**
  73413. * Apply an impulse
  73414. */
  73415. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73416. if (this._physicsEngine) {
  73417. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73418. }
  73419. return this;
  73420. };
  73421. /**
  73422. * A help function to create a joint.
  73423. */
  73424. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73425. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73426. this.addJoint(otherImpostor, joint);
  73427. return this;
  73428. };
  73429. /**
  73430. * Add a joint to this impostor with a different impostor.
  73431. */
  73432. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73433. this._joints.push({
  73434. otherImpostor: otherImpostor,
  73435. joint: joint
  73436. });
  73437. if (this._physicsEngine) {
  73438. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73439. }
  73440. return this;
  73441. };
  73442. /**
  73443. * Will keep this body still, in a sleep mode.
  73444. */
  73445. PhysicsImpostor.prototype.sleep = function () {
  73446. if (this._physicsEngine) {
  73447. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73448. }
  73449. return this;
  73450. };
  73451. /**
  73452. * Wake the body up.
  73453. */
  73454. PhysicsImpostor.prototype.wakeUp = function () {
  73455. if (this._physicsEngine) {
  73456. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73457. }
  73458. return this;
  73459. };
  73460. PhysicsImpostor.prototype.clone = function (newObject) {
  73461. if (!newObject)
  73462. return null;
  73463. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73464. };
  73465. PhysicsImpostor.prototype.dispose = function () {
  73466. var _this = this;
  73467. //no dispose if no physics engine is available.
  73468. if (!this._physicsEngine) {
  73469. return;
  73470. }
  73471. this._joints.forEach(function (j) {
  73472. if (_this._physicsEngine) {
  73473. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73474. }
  73475. });
  73476. //dispose the physics body
  73477. this._physicsEngine.removeImpostor(this);
  73478. if (this.parent) {
  73479. this.parent.forceUpdate();
  73480. }
  73481. else {
  73482. /*this._object.getChildMeshes().forEach(function(mesh) {
  73483. if (mesh.physicsImpostor) {
  73484. if (disposeChildren) {
  73485. mesh.physicsImpostor.dispose();
  73486. mesh.physicsImpostor = null;
  73487. }
  73488. }
  73489. })*/
  73490. }
  73491. this._isDisposed = true;
  73492. };
  73493. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73494. this._deltaPosition.copyFrom(position);
  73495. };
  73496. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73497. if (!this._deltaRotation) {
  73498. this._deltaRotation = new BABYLON.Quaternion();
  73499. }
  73500. this._deltaRotation.copyFrom(rotation);
  73501. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73502. };
  73503. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73504. if (this._physicsEngine) {
  73505. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73506. }
  73507. return this;
  73508. };
  73509. PhysicsImpostor.prototype.getRadius = function () {
  73510. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73511. };
  73512. /**
  73513. * Sync a bone with this impostor
  73514. * @param bone The bone to sync to the impostor.
  73515. * @param boneMesh The mesh that the bone is influencing.
  73516. * @param jointPivot The pivot of the joint / bone in local space.
  73517. * @param distToJoint Optional distance from the impostor to the joint.
  73518. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73519. */
  73520. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73521. var tempVec = PhysicsImpostor._tmpVecs[0];
  73522. var mesh = this.object;
  73523. if (mesh.rotationQuaternion) {
  73524. if (adjustRotation) {
  73525. var tempQuat = PhysicsImpostor._tmpQuat;
  73526. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73527. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73528. }
  73529. else {
  73530. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73531. }
  73532. }
  73533. tempVec.x = 0;
  73534. tempVec.y = 0;
  73535. tempVec.z = 0;
  73536. if (jointPivot) {
  73537. tempVec.x = jointPivot.x;
  73538. tempVec.y = jointPivot.y;
  73539. tempVec.z = jointPivot.z;
  73540. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73541. if (distToJoint === undefined || distToJoint === null) {
  73542. distToJoint = jointPivot.length();
  73543. }
  73544. tempVec.x *= distToJoint;
  73545. tempVec.y *= distToJoint;
  73546. tempVec.z *= distToJoint;
  73547. }
  73548. if (bone.getParent()) {
  73549. tempVec.addInPlace(mesh.getAbsolutePosition());
  73550. bone.setAbsolutePosition(tempVec, boneMesh);
  73551. }
  73552. else {
  73553. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73554. boneMesh.position.x -= tempVec.x;
  73555. boneMesh.position.y -= tempVec.y;
  73556. boneMesh.position.z -= tempVec.z;
  73557. }
  73558. };
  73559. /**
  73560. * Sync impostor to a bone
  73561. * @param bone The bone that the impostor will be synced to.
  73562. * @param boneMesh The mesh that the bone is influencing.
  73563. * @param jointPivot The pivot of the joint / bone in local space.
  73564. * @param distToJoint Optional distance from the impostor to the joint.
  73565. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73566. * @param boneAxis Optional vector3 axis the bone is aligned with
  73567. */
  73568. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73569. var mesh = this.object;
  73570. if (mesh.rotationQuaternion) {
  73571. if (adjustRotation) {
  73572. var tempQuat = PhysicsImpostor._tmpQuat;
  73573. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73574. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73575. }
  73576. else {
  73577. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73578. }
  73579. }
  73580. var pos = PhysicsImpostor._tmpVecs[0];
  73581. var boneDir = PhysicsImpostor._tmpVecs[1];
  73582. if (!boneAxis) {
  73583. boneAxis = PhysicsImpostor._tmpVecs[2];
  73584. boneAxis.x = 0;
  73585. boneAxis.y = 1;
  73586. boneAxis.z = 0;
  73587. }
  73588. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73589. bone.getAbsolutePositionToRef(boneMesh, pos);
  73590. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73591. distToJoint = jointPivot.length();
  73592. }
  73593. if (distToJoint !== undefined && distToJoint !== null) {
  73594. pos.x += boneDir.x * distToJoint;
  73595. pos.y += boneDir.y * distToJoint;
  73596. pos.z += boneDir.z * distToJoint;
  73597. }
  73598. mesh.setAbsolutePosition(pos);
  73599. };
  73600. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73601. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73602. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73603. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73604. //Impostor types
  73605. PhysicsImpostor.NoImpostor = 0;
  73606. PhysicsImpostor.SphereImpostor = 1;
  73607. PhysicsImpostor.BoxImpostor = 2;
  73608. PhysicsImpostor.PlaneImpostor = 3;
  73609. PhysicsImpostor.MeshImpostor = 4;
  73610. PhysicsImpostor.CylinderImpostor = 7;
  73611. PhysicsImpostor.ParticleImpostor = 8;
  73612. PhysicsImpostor.HeightmapImpostor = 9;
  73613. return PhysicsImpostor;
  73614. }());
  73615. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73616. })(BABYLON || (BABYLON = {}));
  73617. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73618. var BABYLON;
  73619. (function (BABYLON) {
  73620. var PhysicsEngine = /** @class */ (function () {
  73621. function PhysicsEngine(gravity, _physicsPlugin) {
  73622. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73623. this._physicsPlugin = _physicsPlugin;
  73624. //new methods and parameters
  73625. this._impostors = [];
  73626. this._joints = [];
  73627. if (!this._physicsPlugin.isSupported()) {
  73628. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73629. + "Please make sure it is included.");
  73630. }
  73631. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73632. this.setGravity(gravity);
  73633. this.setTimeStep();
  73634. }
  73635. PhysicsEngine.prototype.setGravity = function (gravity) {
  73636. this.gravity = gravity;
  73637. this._physicsPlugin.setGravity(this.gravity);
  73638. };
  73639. /**
  73640. * Set the time step of the physics engine.
  73641. * default is 1/60.
  73642. * To slow it down, enter 1/600 for example.
  73643. * To speed it up, 1/30
  73644. * @param {number} newTimeStep the new timestep to apply to this world.
  73645. */
  73646. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73647. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73648. this._physicsPlugin.setTimeStep(newTimeStep);
  73649. };
  73650. /**
  73651. * Get the time step of the physics engine.
  73652. */
  73653. PhysicsEngine.prototype.getTimeStep = function () {
  73654. return this._physicsPlugin.getTimeStep();
  73655. };
  73656. PhysicsEngine.prototype.dispose = function () {
  73657. this._impostors.forEach(function (impostor) {
  73658. impostor.dispose();
  73659. });
  73660. this._physicsPlugin.dispose();
  73661. };
  73662. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73663. return this._physicsPlugin.name;
  73664. };
  73665. /**
  73666. * Adding a new impostor for the impostor tracking.
  73667. * This will be done by the impostor itself.
  73668. * @param {PhysicsImpostor} impostor the impostor to add
  73669. */
  73670. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73671. impostor.uniqueId = this._impostors.push(impostor);
  73672. //if no parent, generate the body
  73673. if (!impostor.parent) {
  73674. this._physicsPlugin.generatePhysicsBody(impostor);
  73675. }
  73676. };
  73677. /**
  73678. * Remove an impostor from the engine.
  73679. * This impostor and its mesh will not longer be updated by the physics engine.
  73680. * @param {PhysicsImpostor} impostor the impostor to remove
  73681. */
  73682. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73683. var index = this._impostors.indexOf(impostor);
  73684. if (index > -1) {
  73685. var removed = this._impostors.splice(index, 1);
  73686. //Is it needed?
  73687. if (removed.length) {
  73688. //this will also remove it from the world.
  73689. removed[0].physicsBody = null;
  73690. }
  73691. }
  73692. };
  73693. /**
  73694. * Add a joint to the physics engine
  73695. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73696. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73697. * @param {PhysicsJoint} the joint that will connect both impostors.
  73698. */
  73699. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73700. var impostorJoint = {
  73701. mainImpostor: mainImpostor,
  73702. connectedImpostor: connectedImpostor,
  73703. joint: joint
  73704. };
  73705. joint.physicsPlugin = this._physicsPlugin;
  73706. this._joints.push(impostorJoint);
  73707. this._physicsPlugin.generateJoint(impostorJoint);
  73708. };
  73709. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73710. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73711. return (impostorJoint.connectedImpostor === connectedImpostor
  73712. && impostorJoint.joint === joint
  73713. && impostorJoint.mainImpostor === mainImpostor);
  73714. });
  73715. if (matchingJoints.length) {
  73716. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73717. //TODO remove it from the list as well
  73718. }
  73719. };
  73720. /**
  73721. * Called by the scene. no need to call it.
  73722. */
  73723. PhysicsEngine.prototype._step = function (delta) {
  73724. var _this = this;
  73725. //check if any mesh has no body / requires an update
  73726. this._impostors.forEach(function (impostor) {
  73727. if (impostor.isBodyInitRequired()) {
  73728. _this._physicsPlugin.generatePhysicsBody(impostor);
  73729. }
  73730. });
  73731. if (delta > 0.1) {
  73732. delta = 0.1;
  73733. }
  73734. else if (delta <= 0) {
  73735. delta = 1.0 / 60.0;
  73736. }
  73737. this._physicsPlugin.executeStep(delta, this._impostors);
  73738. };
  73739. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73740. return this._physicsPlugin;
  73741. };
  73742. PhysicsEngine.prototype.getImpostors = function () {
  73743. return this._impostors;
  73744. };
  73745. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73746. for (var i = 0; i < this._impostors.length; ++i) {
  73747. if (this._impostors[i].object === object) {
  73748. return this._impostors[i];
  73749. }
  73750. }
  73751. return null;
  73752. };
  73753. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73754. for (var i = 0; i < this._impostors.length; ++i) {
  73755. if (this._impostors[i].physicsBody === body) {
  73756. return this._impostors[i];
  73757. }
  73758. }
  73759. return null;
  73760. };
  73761. // Statics
  73762. PhysicsEngine.Epsilon = 0.001;
  73763. return PhysicsEngine;
  73764. }());
  73765. BABYLON.PhysicsEngine = PhysicsEngine;
  73766. })(BABYLON || (BABYLON = {}));
  73767. //# sourceMappingURL=babylon.physicsEngine.js.map
  73768. var BABYLON;
  73769. (function (BABYLON) {
  73770. var PhysicsHelper = /** @class */ (function () {
  73771. function PhysicsHelper(scene) {
  73772. this._scene = scene;
  73773. this._physicsEngine = this._scene.getPhysicsEngine();
  73774. if (!this._physicsEngine) {
  73775. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73776. }
  73777. }
  73778. /**
  73779. * @param {Vector3} origin the origin of the explosion
  73780. * @param {number} radius the explosion radius
  73781. * @param {number} strength the explosion strength
  73782. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73783. */
  73784. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73785. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73786. if (!this._physicsEngine) {
  73787. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73788. return null;
  73789. }
  73790. var impostors = this._physicsEngine.getImpostors();
  73791. if (impostors.length === 0) {
  73792. return null;
  73793. }
  73794. var event = new PhysicsRadialExplosionEvent(this._scene);
  73795. impostors.forEach(function (impostor) {
  73796. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73797. if (!impostorForceAndContactPoint) {
  73798. return;
  73799. }
  73800. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73801. });
  73802. event.dispose(false);
  73803. return event;
  73804. };
  73805. /**
  73806. * @param {Vector3} origin the origin of the explosion
  73807. * @param {number} radius the explosion radius
  73808. * @param {number} strength the explosion strength
  73809. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73810. */
  73811. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73812. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73813. if (!this._physicsEngine) {
  73814. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73815. return null;
  73816. }
  73817. var impostors = this._physicsEngine.getImpostors();
  73818. if (impostors.length === 0) {
  73819. return null;
  73820. }
  73821. var event = new PhysicsRadialExplosionEvent(this._scene);
  73822. impostors.forEach(function (impostor) {
  73823. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73824. if (!impostorForceAndContactPoint) {
  73825. return;
  73826. }
  73827. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73828. });
  73829. event.dispose(false);
  73830. return event;
  73831. };
  73832. /**
  73833. * @param {Vector3} origin the origin of the explosion
  73834. * @param {number} radius the explosion radius
  73835. * @param {number} strength the explosion strength
  73836. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73837. */
  73838. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73839. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73840. if (!this._physicsEngine) {
  73841. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73842. return null;
  73843. }
  73844. var impostors = this._physicsEngine.getImpostors();
  73845. if (impostors.length === 0) {
  73846. return null;
  73847. }
  73848. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73849. event.dispose(false);
  73850. return event;
  73851. };
  73852. /**
  73853. * @param {Vector3} origin the origin of the updraft
  73854. * @param {number} radius the radius of the updraft
  73855. * @param {number} strength the strength of the updraft
  73856. * @param {number} height the height of the updraft
  73857. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73858. */
  73859. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73860. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73861. if (!this._physicsEngine) {
  73862. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73863. return null;
  73864. }
  73865. if (this._physicsEngine.getImpostors().length === 0) {
  73866. return null;
  73867. }
  73868. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73869. event.dispose(false);
  73870. return event;
  73871. };
  73872. /**
  73873. * @param {Vector3} origin the of the vortex
  73874. * @param {number} radius the radius of the vortex
  73875. * @param {number} strength the strength of the vortex
  73876. * @param {number} height the height of the vortex
  73877. */
  73878. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  73879. if (!this._physicsEngine) {
  73880. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73881. return null;
  73882. }
  73883. if (this._physicsEngine.getImpostors().length === 0) {
  73884. return null;
  73885. }
  73886. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  73887. event.dispose(false);
  73888. return event;
  73889. };
  73890. return PhysicsHelper;
  73891. }());
  73892. BABYLON.PhysicsHelper = PhysicsHelper;
  73893. /***** Radial explosion *****/
  73894. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  73895. function PhysicsRadialExplosionEvent(scene) {
  73896. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  73897. this._rays = [];
  73898. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  73899. this._scene = scene;
  73900. }
  73901. /**
  73902. * Returns the data related to the radial explosion event (sphere & rays).
  73903. * @returns {PhysicsRadialExplosionEventData}
  73904. */
  73905. PhysicsRadialExplosionEvent.prototype.getData = function () {
  73906. this._dataFetched = true;
  73907. return {
  73908. sphere: this._sphere,
  73909. rays: this._rays,
  73910. };
  73911. };
  73912. /**
  73913. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  73914. * @param impostor
  73915. * @param {Vector3} origin the origin of the explosion
  73916. * @param {number} radius the explosion radius
  73917. * @param {number} strength the explosion strength
  73918. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  73919. * @returns {Nullable<PhysicsForceAndContactPoint>}
  73920. */
  73921. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  73922. if (impostor.mass === 0) {
  73923. return null;
  73924. }
  73925. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  73926. return null;
  73927. }
  73928. if (impostor.object.getClassName() !== 'Mesh') {
  73929. return null;
  73930. }
  73931. var impostorObject = impostor.object;
  73932. var impostorObjectCenter = impostor.getObjectCenter();
  73933. var direction = impostorObjectCenter.subtract(origin);
  73934. var ray = new BABYLON.Ray(origin, direction, radius);
  73935. this._rays.push(ray);
  73936. var hit = ray.intersectsMesh(impostorObject);
  73937. var contactPoint = hit.pickedPoint;
  73938. if (!contactPoint) {
  73939. return null;
  73940. }
  73941. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  73942. if (distanceFromOrigin > radius) {
  73943. return null;
  73944. }
  73945. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  73946. ? strength
  73947. : strength * (1 - (distanceFromOrigin / radius));
  73948. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73949. return { force: force, contactPoint: contactPoint };
  73950. };
  73951. /**
  73952. * Disposes the sphere.
  73953. * @param {bolean} force
  73954. */
  73955. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  73956. var _this = this;
  73957. if (force === void 0) { force = true; }
  73958. if (force) {
  73959. this._sphere.dispose();
  73960. }
  73961. else {
  73962. setTimeout(function () {
  73963. if (!_this._dataFetched) {
  73964. _this._sphere.dispose();
  73965. }
  73966. }, 0);
  73967. }
  73968. };
  73969. /*** Helpers ***/
  73970. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  73971. if (!this._sphere) {
  73972. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  73973. this._sphere.isVisible = false;
  73974. }
  73975. };
  73976. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  73977. var impostorObject = impostor.object;
  73978. this._prepareSphere();
  73979. this._sphere.position = origin;
  73980. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  73981. this._sphere._updateBoundingInfo();
  73982. this._sphere.computeWorldMatrix(true);
  73983. return this._sphere.intersectsMesh(impostorObject, true);
  73984. };
  73985. return PhysicsRadialExplosionEvent;
  73986. }());
  73987. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  73988. /***** Gravitational Field *****/
  73989. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  73990. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  73991. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73992. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73993. this._physicsHelper = physicsHelper;
  73994. this._scene = scene;
  73995. this._origin = origin;
  73996. this._radius = radius;
  73997. this._strength = strength;
  73998. this._falloff = falloff;
  73999. this._tickCallback = this._tick.bind(this);
  74000. }
  74001. /**
  74002. * Returns the data related to the gravitational field event (sphere).
  74003. * @returns {PhysicsGravitationalFieldEventData}
  74004. */
  74005. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74006. this._dataFetched = true;
  74007. return {
  74008. sphere: this._sphere,
  74009. };
  74010. };
  74011. /**
  74012. * Enables the gravitational field.
  74013. */
  74014. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74015. this._tickCallback.call(this);
  74016. this._scene.registerBeforeRender(this._tickCallback);
  74017. };
  74018. /**
  74019. * Disables the gravitational field.
  74020. */
  74021. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74022. this._scene.unregisterBeforeRender(this._tickCallback);
  74023. };
  74024. /**
  74025. * Disposes the sphere.
  74026. * @param {bolean} force
  74027. */
  74028. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74029. var _this = this;
  74030. if (force === void 0) { force = true; }
  74031. if (force) {
  74032. this._sphere.dispose();
  74033. }
  74034. else {
  74035. setTimeout(function () {
  74036. if (!_this._dataFetched) {
  74037. _this._sphere.dispose();
  74038. }
  74039. }, 0);
  74040. }
  74041. };
  74042. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74043. // Since the params won't change, we fetch the event only once
  74044. if (this._sphere) {
  74045. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74046. }
  74047. else {
  74048. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74049. if (radialExplosionEvent) {
  74050. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74051. }
  74052. }
  74053. };
  74054. return PhysicsGravitationalFieldEvent;
  74055. }());
  74056. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74057. /***** Updraft *****/
  74058. var PhysicsUpdraftEvent = /** @class */ (function () {
  74059. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74060. this._scene = _scene;
  74061. this._origin = _origin;
  74062. this._radius = _radius;
  74063. this._strength = _strength;
  74064. this._height = _height;
  74065. this._updraftMode = _updraftMode;
  74066. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74067. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74068. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74069. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74070. this._physicsEngine = this._scene.getPhysicsEngine();
  74071. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74072. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74073. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74074. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74075. }
  74076. this._tickCallback = this._tick.bind(this);
  74077. }
  74078. /**
  74079. * Returns the data related to the updraft event (cylinder).
  74080. * @returns {PhysicsUpdraftEventData}
  74081. */
  74082. PhysicsUpdraftEvent.prototype.getData = function () {
  74083. this._dataFetched = true;
  74084. return {
  74085. cylinder: this._cylinder,
  74086. };
  74087. };
  74088. /**
  74089. * Enables the updraft.
  74090. */
  74091. PhysicsUpdraftEvent.prototype.enable = function () {
  74092. this._tickCallback.call(this);
  74093. this._scene.registerBeforeRender(this._tickCallback);
  74094. };
  74095. /**
  74096. * Disables the cortex.
  74097. */
  74098. PhysicsUpdraftEvent.prototype.disable = function () {
  74099. this._scene.unregisterBeforeRender(this._tickCallback);
  74100. };
  74101. /**
  74102. * Disposes the sphere.
  74103. * @param {bolean} force
  74104. */
  74105. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74106. var _this = this;
  74107. if (force === void 0) { force = true; }
  74108. if (force) {
  74109. this._cylinder.dispose();
  74110. }
  74111. else {
  74112. setTimeout(function () {
  74113. if (!_this._dataFetched) {
  74114. _this._cylinder.dispose();
  74115. }
  74116. }, 0);
  74117. }
  74118. };
  74119. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74120. if (impostor.mass === 0) {
  74121. return null;
  74122. }
  74123. if (!this._intersectsWithCylinder(impostor)) {
  74124. return null;
  74125. }
  74126. var impostorObjectCenter = impostor.getObjectCenter();
  74127. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74128. var direction = this._originDirection;
  74129. }
  74130. else {
  74131. var direction = impostorObjectCenter.subtract(this._originTop);
  74132. }
  74133. var multiplier = this._strength * -1;
  74134. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74135. return { force: force, contactPoint: impostorObjectCenter };
  74136. };
  74137. PhysicsUpdraftEvent.prototype._tick = function () {
  74138. var _this = this;
  74139. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74140. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74141. if (!impostorForceAndContactPoint) {
  74142. return;
  74143. }
  74144. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74145. });
  74146. };
  74147. /*** Helpers ***/
  74148. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74149. if (!this._cylinder) {
  74150. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74151. height: this._height,
  74152. diameter: this._radius * 2,
  74153. }, this._scene);
  74154. this._cylinder.isVisible = false;
  74155. }
  74156. };
  74157. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74158. var impostorObject = impostor.object;
  74159. this._prepareCylinder();
  74160. this._cylinder.position = this._cylinderPosition;
  74161. return this._cylinder.intersectsMesh(impostorObject, true);
  74162. };
  74163. return PhysicsUpdraftEvent;
  74164. }());
  74165. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74166. /***** Vortex *****/
  74167. var PhysicsVortexEvent = /** @class */ (function () {
  74168. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74169. this._scene = _scene;
  74170. this._origin = _origin;
  74171. this._radius = _radius;
  74172. this._strength = _strength;
  74173. this._height = _height;
  74174. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74175. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74176. this._updraftMultiplier = 0.02;
  74177. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74178. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74179. this._physicsEngine = this._scene.getPhysicsEngine();
  74180. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74181. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74182. this._tickCallback = this._tick.bind(this);
  74183. }
  74184. /**
  74185. * Returns the data related to the vortex event (cylinder).
  74186. * @returns {PhysicsVortexEventData}
  74187. */
  74188. PhysicsVortexEvent.prototype.getData = function () {
  74189. this._dataFetched = true;
  74190. return {
  74191. cylinder: this._cylinder,
  74192. };
  74193. };
  74194. /**
  74195. * Enables the vortex.
  74196. */
  74197. PhysicsVortexEvent.prototype.enable = function () {
  74198. this._tickCallback.call(this);
  74199. this._scene.registerBeforeRender(this._tickCallback);
  74200. };
  74201. /**
  74202. * Disables the cortex.
  74203. */
  74204. PhysicsVortexEvent.prototype.disable = function () {
  74205. this._scene.unregisterBeforeRender(this._tickCallback);
  74206. };
  74207. /**
  74208. * Disposes the sphere.
  74209. * @param {bolean} force
  74210. */
  74211. PhysicsVortexEvent.prototype.dispose = function (force) {
  74212. var _this = this;
  74213. if (force === void 0) { force = true; }
  74214. if (force) {
  74215. this._cylinder.dispose();
  74216. }
  74217. else {
  74218. setTimeout(function () {
  74219. if (!_this._dataFetched) {
  74220. _this._cylinder.dispose();
  74221. }
  74222. }, 0);
  74223. }
  74224. };
  74225. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74226. if (impostor.mass === 0) {
  74227. return null;
  74228. }
  74229. if (!this._intersectsWithCylinder(impostor)) {
  74230. return null;
  74231. }
  74232. if (impostor.object.getClassName() !== 'Mesh') {
  74233. return null;
  74234. }
  74235. var impostorObject = impostor.object;
  74236. var impostorObjectCenter = impostor.getObjectCenter();
  74237. 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)
  74238. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74239. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74240. var hit = ray.intersectsMesh(impostorObject);
  74241. var contactPoint = hit.pickedPoint;
  74242. if (!contactPoint) {
  74243. return null;
  74244. }
  74245. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74246. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74247. var directionToOrigin = contactPoint.normalize();
  74248. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74249. directionToOrigin = directionToOrigin.negate();
  74250. }
  74251. // TODO: find a more physically based solution
  74252. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74253. var forceX = directionToOrigin.x * this._strength / 8;
  74254. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74255. var forceZ = directionToOrigin.z * this._strength / 8;
  74256. }
  74257. else {
  74258. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74259. var forceY = this._originTop.y * this._updraftMultiplier;
  74260. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74261. }
  74262. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74263. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74264. return { force: force, contactPoint: impostorObjectCenter };
  74265. };
  74266. PhysicsVortexEvent.prototype._tick = function () {
  74267. var _this = this;
  74268. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74269. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74270. if (!impostorForceAndContactPoint) {
  74271. return;
  74272. }
  74273. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74274. });
  74275. };
  74276. /*** Helpers ***/
  74277. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74278. if (!this._cylinder) {
  74279. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74280. height: this._height,
  74281. diameter: this._radius * 2,
  74282. }, this._scene);
  74283. this._cylinder.isVisible = false;
  74284. }
  74285. };
  74286. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74287. var impostorObject = impostor.object;
  74288. this._prepareCylinder();
  74289. this._cylinder.position = this._cylinderPosition;
  74290. return this._cylinder.intersectsMesh(impostorObject, true);
  74291. };
  74292. return PhysicsVortexEvent;
  74293. }());
  74294. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74295. /***** Enums *****/
  74296. /**
  74297. * The strenght of the force in correspondence to the distance of the affected object
  74298. */
  74299. var PhysicsRadialImpulseFalloff;
  74300. (function (PhysicsRadialImpulseFalloff) {
  74301. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74302. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74303. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74304. /**
  74305. * The strenght of the force in correspondence to the distance of the affected object
  74306. */
  74307. var PhysicsUpdraftMode;
  74308. (function (PhysicsUpdraftMode) {
  74309. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74310. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74311. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74312. })(BABYLON || (BABYLON = {}));
  74313. //# sourceMappingURL=babylon.physicsHelper.js.map
  74314. var BABYLON;
  74315. (function (BABYLON) {
  74316. var CannonJSPlugin = /** @class */ (function () {
  74317. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74318. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74319. if (iterations === void 0) { iterations = 10; }
  74320. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74321. this.name = "CannonJSPlugin";
  74322. this._physicsMaterials = new Array();
  74323. this._fixedTimeStep = 1 / 60;
  74324. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74325. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74326. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74327. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74328. this._tmpPosition = BABYLON.Vector3.Zero();
  74329. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74330. this._tmpUnityRotation = new BABYLON.Quaternion();
  74331. if (!this.isSupported()) {
  74332. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74333. return;
  74334. }
  74335. this._extendNamespace();
  74336. this.world = new this.BJSCANNON.World();
  74337. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74338. this.world.solver.iterations = iterations;
  74339. }
  74340. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74341. this.world.gravity.copy(gravity);
  74342. };
  74343. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74344. this._fixedTimeStep = timeStep;
  74345. };
  74346. CannonJSPlugin.prototype.getTimeStep = function () {
  74347. return this._fixedTimeStep;
  74348. };
  74349. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74350. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74351. };
  74352. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74353. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74354. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74355. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74356. };
  74357. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74358. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74359. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74360. impostor.physicsBody.applyForce(impulse, worldPoint);
  74361. };
  74362. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74363. //parent-child relationship. Does this impostor has a parent impostor?
  74364. if (impostor.parent) {
  74365. if (impostor.physicsBody) {
  74366. this.removePhysicsBody(impostor);
  74367. //TODO is that needed?
  74368. impostor.forceUpdate();
  74369. }
  74370. return;
  74371. }
  74372. //should a new body be created for this impostor?
  74373. if (impostor.isBodyInitRequired()) {
  74374. var shape = this._createShape(impostor);
  74375. //unregister events, if body is being changed
  74376. var oldBody = impostor.physicsBody;
  74377. if (oldBody) {
  74378. this.removePhysicsBody(impostor);
  74379. }
  74380. //create the body and material
  74381. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74382. var bodyCreationObject = {
  74383. mass: impostor.getParam("mass"),
  74384. material: material
  74385. };
  74386. // A simple extend, in case native options were used.
  74387. var nativeOptions = impostor.getParam("nativeOptions");
  74388. for (var key in nativeOptions) {
  74389. if (nativeOptions.hasOwnProperty(key)) {
  74390. bodyCreationObject[key] = nativeOptions[key];
  74391. }
  74392. }
  74393. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74394. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74395. this.world.addEventListener("preStep", impostor.beforeStep);
  74396. this.world.addEventListener("postStep", impostor.afterStep);
  74397. impostor.physicsBody.addShape(shape);
  74398. this.world.add(impostor.physicsBody);
  74399. //try to keep the body moving in the right direction by taking old properties.
  74400. //Should be tested!
  74401. if (oldBody) {
  74402. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74403. impostor.physicsBody[param].copy(oldBody[param]);
  74404. });
  74405. }
  74406. this._processChildMeshes(impostor);
  74407. }
  74408. //now update the body's transformation
  74409. this._updatePhysicsBodyTransformation(impostor);
  74410. };
  74411. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74412. var _this = this;
  74413. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74414. var currentRotation = mainImpostor.object.rotationQuaternion;
  74415. if (meshChildren.length) {
  74416. var processMesh = function (localPosition, mesh) {
  74417. if (!currentRotation || !mesh.rotationQuaternion) {
  74418. return;
  74419. }
  74420. var childImpostor = mesh.getPhysicsImpostor();
  74421. if (childImpostor) {
  74422. var parent = childImpostor.parent;
  74423. if (parent !== mainImpostor) {
  74424. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74425. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74426. if (childImpostor.physicsBody) {
  74427. _this.removePhysicsBody(childImpostor);
  74428. childImpostor.physicsBody = null;
  74429. }
  74430. childImpostor.parent = mainImpostor;
  74431. childImpostor.resetUpdateFlags();
  74432. 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));
  74433. //Add the mass of the children.
  74434. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74435. }
  74436. }
  74437. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74438. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74439. };
  74440. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74441. }
  74442. };
  74443. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74444. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74445. this.world.removeEventListener("preStep", impostor.beforeStep);
  74446. this.world.removeEventListener("postStep", impostor.afterStep);
  74447. this.world.remove(impostor.physicsBody);
  74448. };
  74449. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74450. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74451. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74452. if (!mainBody || !connectedBody) {
  74453. return;
  74454. }
  74455. var constraint;
  74456. var jointData = impostorJoint.joint.jointData;
  74457. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74458. var constraintData = {
  74459. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74460. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74461. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74462. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74463. maxForce: jointData.nativeParams.maxForce,
  74464. collideConnected: !!jointData.collision
  74465. };
  74466. switch (impostorJoint.joint.type) {
  74467. case BABYLON.PhysicsJoint.HingeJoint:
  74468. case BABYLON.PhysicsJoint.Hinge2Joint:
  74469. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74470. break;
  74471. case BABYLON.PhysicsJoint.DistanceJoint:
  74472. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74473. break;
  74474. case BABYLON.PhysicsJoint.SpringJoint:
  74475. var springData = jointData;
  74476. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74477. restLength: springData.length,
  74478. stiffness: springData.stiffness,
  74479. damping: springData.damping,
  74480. localAnchorA: constraintData.pivotA,
  74481. localAnchorB: constraintData.pivotB
  74482. });
  74483. break;
  74484. case BABYLON.PhysicsJoint.LockJoint:
  74485. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74486. break;
  74487. case BABYLON.PhysicsJoint.PointToPointJoint:
  74488. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74489. default:
  74490. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74491. break;
  74492. }
  74493. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74494. constraint.collideConnected = !!jointData.collision;
  74495. impostorJoint.joint.physicsJoint = constraint;
  74496. //don't add spring as constraint, as it is not one.
  74497. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74498. this.world.addConstraint(constraint);
  74499. }
  74500. else {
  74501. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74502. constraint.applyForce();
  74503. });
  74504. }
  74505. };
  74506. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74507. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74508. };
  74509. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74510. var index;
  74511. var mat;
  74512. for (index = 0; index < this._physicsMaterials.length; index++) {
  74513. mat = this._physicsMaterials[index];
  74514. if (mat.friction === friction && mat.restitution === restitution) {
  74515. return mat;
  74516. }
  74517. }
  74518. var currentMat = new this.BJSCANNON.Material(name);
  74519. currentMat.friction = friction;
  74520. currentMat.restitution = restitution;
  74521. this._physicsMaterials.push(currentMat);
  74522. return currentMat;
  74523. };
  74524. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74525. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74526. };
  74527. CannonJSPlugin.prototype._createShape = function (impostor) {
  74528. var object = impostor.object;
  74529. var returnValue;
  74530. var extendSize = impostor.getObjectExtendSize();
  74531. switch (impostor.type) {
  74532. case BABYLON.PhysicsImpostor.SphereImpostor:
  74533. var radiusX = extendSize.x;
  74534. var radiusY = extendSize.y;
  74535. var radiusZ = extendSize.z;
  74536. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74537. break;
  74538. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74539. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74540. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74541. break;
  74542. case BABYLON.PhysicsImpostor.BoxImpostor:
  74543. var box = extendSize.scale(0.5);
  74544. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74545. break;
  74546. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74547. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74548. returnValue = new this.BJSCANNON.Plane();
  74549. break;
  74550. case BABYLON.PhysicsImpostor.MeshImpostor:
  74551. // should transform the vertex data to world coordinates!!
  74552. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74553. var rawFaces = object.getIndices ? object.getIndices() : [];
  74554. if (!rawVerts)
  74555. return;
  74556. // get only scale! so the object could transform correctly.
  74557. var oldPosition = object.position.clone();
  74558. var oldRotation = object.rotation && object.rotation.clone();
  74559. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74560. object.position.copyFromFloats(0, 0, 0);
  74561. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74562. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74563. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74564. var transform = object.computeWorldMatrix(true);
  74565. // convert rawVerts to object space
  74566. var temp = new Array();
  74567. var index;
  74568. for (index = 0; index < rawVerts.length; index += 3) {
  74569. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74570. }
  74571. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74572. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74573. //now set back the transformation!
  74574. object.position.copyFrom(oldPosition);
  74575. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74576. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74577. break;
  74578. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74579. var oldPosition2 = object.position.clone();
  74580. var oldRotation2 = object.rotation && object.rotation.clone();
  74581. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74582. object.position.copyFromFloats(0, 0, 0);
  74583. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74584. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74585. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74586. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74587. returnValue = this._createHeightmap(object);
  74588. object.position.copyFrom(oldPosition2);
  74589. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74590. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74591. object.computeWorldMatrix(true);
  74592. break;
  74593. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74594. returnValue = new this.BJSCANNON.Particle();
  74595. break;
  74596. }
  74597. return returnValue;
  74598. };
  74599. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74600. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74601. var transform = object.computeWorldMatrix(true);
  74602. // convert rawVerts to object space
  74603. var temp = new Array();
  74604. var index;
  74605. for (index = 0; index < pos.length; index += 3) {
  74606. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74607. }
  74608. pos = temp;
  74609. var matrix = new Array();
  74610. //For now pointDepth will not be used and will be automatically calculated.
  74611. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74612. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74613. var boundingInfo = object.getBoundingInfo();
  74614. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74615. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74616. var elementSize = dim * 2 / arraySize;
  74617. for (var i = 0; i < pos.length; i = i + 3) {
  74618. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74619. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74620. var y = -pos[i + 2] + minY;
  74621. if (!matrix[x]) {
  74622. matrix[x] = [];
  74623. }
  74624. if (!matrix[x][z]) {
  74625. matrix[x][z] = y;
  74626. }
  74627. matrix[x][z] = Math.max(y, matrix[x][z]);
  74628. }
  74629. for (var x = 0; x <= arraySize; ++x) {
  74630. if (!matrix[x]) {
  74631. var loc = 1;
  74632. while (!matrix[(x + loc) % arraySize]) {
  74633. loc++;
  74634. }
  74635. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74636. //console.log("missing x", x);
  74637. }
  74638. for (var z = 0; z <= arraySize; ++z) {
  74639. if (!matrix[x][z]) {
  74640. var loc = 1;
  74641. var newValue;
  74642. while (newValue === undefined) {
  74643. newValue = matrix[x][(z + loc++) % arraySize];
  74644. }
  74645. matrix[x][z] = newValue;
  74646. }
  74647. }
  74648. }
  74649. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74650. elementSize: elementSize
  74651. });
  74652. //For future reference, needed for body transformation
  74653. shape.minY = minY;
  74654. return shape;
  74655. };
  74656. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74657. var object = impostor.object;
  74658. //make sure it is updated...
  74659. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74660. // The delta between the mesh position and the mesh bounding box center
  74661. var bInfo = object.getBoundingInfo();
  74662. if (!bInfo)
  74663. return;
  74664. var center = impostor.getObjectCenter();
  74665. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74666. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74667. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74668. this._tmpPosition.copyFrom(center);
  74669. var quaternion = object.rotationQuaternion;
  74670. if (!quaternion) {
  74671. return;
  74672. }
  74673. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74674. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74675. //-90 DEG in X, precalculated
  74676. quaternion = quaternion.multiply(this._minus90X);
  74677. //Invert! (Precalculated, 90 deg in X)
  74678. //No need to clone. this will never change.
  74679. impostor.setDeltaRotation(this._plus90X);
  74680. }
  74681. //If it is a heightfield, if should be centered.
  74682. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74683. var mesh = object;
  74684. var boundingInfo = mesh.getBoundingInfo();
  74685. //calculate the correct body position:
  74686. var rotationQuaternion = mesh.rotationQuaternion;
  74687. mesh.rotationQuaternion = this._tmpUnityRotation;
  74688. mesh.computeWorldMatrix(true);
  74689. //get original center with no rotation
  74690. var c = center.clone();
  74691. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74692. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74693. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74694. mesh.setPreTransformMatrix(p);
  74695. mesh.computeWorldMatrix(true);
  74696. //calculate the translation
  74697. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74698. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74699. //add it inverted to the delta
  74700. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74701. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74702. //rotation is back
  74703. mesh.rotationQuaternion = rotationQuaternion;
  74704. mesh.setPreTransformMatrix(oldPivot);
  74705. mesh.computeWorldMatrix(true);
  74706. }
  74707. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74708. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74709. //this._tmpPosition.copyFrom(object.position);
  74710. }
  74711. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74712. //Now update the impostor object
  74713. impostor.physicsBody.position.copy(this._tmpPosition);
  74714. impostor.physicsBody.quaternion.copy(quaternion);
  74715. };
  74716. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74717. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74718. if (impostor.object.rotationQuaternion) {
  74719. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74720. }
  74721. };
  74722. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74723. impostor.physicsBody.position.copy(newPosition);
  74724. impostor.physicsBody.quaternion.copy(newRotation);
  74725. };
  74726. CannonJSPlugin.prototype.isSupported = function () {
  74727. return this.BJSCANNON !== undefined;
  74728. };
  74729. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74730. impostor.physicsBody.velocity.copy(velocity);
  74731. };
  74732. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74733. impostor.physicsBody.angularVelocity.copy(velocity);
  74734. };
  74735. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74736. var v = impostor.physicsBody.velocity;
  74737. if (!v) {
  74738. return null;
  74739. }
  74740. return new BABYLON.Vector3(v.x, v.y, v.z);
  74741. };
  74742. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74743. var v = impostor.physicsBody.angularVelocity;
  74744. if (!v) {
  74745. return null;
  74746. }
  74747. return new BABYLON.Vector3(v.x, v.y, v.z);
  74748. };
  74749. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74750. impostor.physicsBody.mass = mass;
  74751. impostor.physicsBody.updateMassProperties();
  74752. };
  74753. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74754. return impostor.physicsBody.mass;
  74755. };
  74756. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74757. return impostor.physicsBody.material.friction;
  74758. };
  74759. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74760. impostor.physicsBody.material.friction = friction;
  74761. };
  74762. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74763. return impostor.physicsBody.material.restitution;
  74764. };
  74765. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74766. impostor.physicsBody.material.restitution = restitution;
  74767. };
  74768. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74769. impostor.physicsBody.sleep();
  74770. };
  74771. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74772. impostor.physicsBody.wakeUp();
  74773. };
  74774. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74775. joint.physicsJoint.distance = maxDistance;
  74776. };
  74777. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74778. // if (!motorIndex) {
  74779. // joint.physicsJoint.enableMotor();
  74780. // }
  74781. // }
  74782. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74783. // if (!motorIndex) {
  74784. // joint.physicsJoint.disableMotor();
  74785. // }
  74786. // }
  74787. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74788. if (!motorIndex) {
  74789. joint.physicsJoint.enableMotor();
  74790. joint.physicsJoint.setMotorSpeed(speed);
  74791. if (maxForce) {
  74792. this.setLimit(joint, maxForce);
  74793. }
  74794. }
  74795. };
  74796. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74797. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74798. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74799. };
  74800. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74801. var body = impostor.physicsBody;
  74802. mesh.position.x = body.position.x;
  74803. mesh.position.y = body.position.y;
  74804. mesh.position.z = body.position.z;
  74805. if (mesh.rotationQuaternion) {
  74806. mesh.rotationQuaternion.x = body.quaternion.x;
  74807. mesh.rotationQuaternion.y = body.quaternion.y;
  74808. mesh.rotationQuaternion.z = body.quaternion.z;
  74809. mesh.rotationQuaternion.w = body.quaternion.w;
  74810. }
  74811. };
  74812. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74813. var shape = impostor.physicsBody.shapes[0];
  74814. return shape.boundingSphereRadius;
  74815. };
  74816. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74817. var shape = impostor.physicsBody.shapes[0];
  74818. result.x = shape.halfExtents.x * 2;
  74819. result.y = shape.halfExtents.y * 2;
  74820. result.z = shape.halfExtents.z * 2;
  74821. };
  74822. CannonJSPlugin.prototype.dispose = function () {
  74823. };
  74824. CannonJSPlugin.prototype._extendNamespace = function () {
  74825. //this will force cannon to execute at least one step when using interpolation
  74826. var step_tmp1 = new this.BJSCANNON.Vec3();
  74827. var Engine = this.BJSCANNON;
  74828. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74829. maxSubSteps = maxSubSteps || 10;
  74830. timeSinceLastCalled = timeSinceLastCalled || 0;
  74831. if (timeSinceLastCalled === 0) {
  74832. this.internalStep(dt);
  74833. this.time += dt;
  74834. }
  74835. else {
  74836. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74837. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74838. var t0 = performance.now();
  74839. for (var i = 0; i !== internalSteps; i++) {
  74840. this.internalStep(dt);
  74841. if (performance.now() - t0 > dt * 1000) {
  74842. break;
  74843. }
  74844. }
  74845. this.time += timeSinceLastCalled;
  74846. var h = this.time % dt;
  74847. var h_div_dt = h / dt;
  74848. var interpvelo = step_tmp1;
  74849. var bodies = this.bodies;
  74850. for (var j = 0; j !== bodies.length; j++) {
  74851. var b = bodies[j];
  74852. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74853. b.position.vsub(b.previousPosition, interpvelo);
  74854. interpvelo.scale(h_div_dt, interpvelo);
  74855. b.position.vadd(interpvelo, b.interpolatedPosition);
  74856. }
  74857. else {
  74858. b.interpolatedPosition.copy(b.position);
  74859. b.interpolatedQuaternion.copy(b.quaternion);
  74860. }
  74861. }
  74862. }
  74863. };
  74864. };
  74865. return CannonJSPlugin;
  74866. }());
  74867. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74868. })(BABYLON || (BABYLON = {}));
  74869. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74870. var BABYLON;
  74871. (function (BABYLON) {
  74872. var OimoJSPlugin = /** @class */ (function () {
  74873. function OimoJSPlugin(iterations) {
  74874. this.name = "OimoJSPlugin";
  74875. this._tmpImpostorsArray = [];
  74876. this._tmpPositionVector = BABYLON.Vector3.Zero();
  74877. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  74878. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  74879. this.world.worldscale(1);
  74880. this.world.clear();
  74881. //making sure no stats are calculated
  74882. this.world.isNoStat = true;
  74883. }
  74884. OimoJSPlugin.prototype.setGravity = function (gravity) {
  74885. this.world.gravity.copy(gravity);
  74886. };
  74887. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  74888. this.world.timeStep = timeStep;
  74889. };
  74890. OimoJSPlugin.prototype.getTimeStep = function () {
  74891. return this.world.timeStep;
  74892. };
  74893. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  74894. var _this = this;
  74895. impostors.forEach(function (impostor) {
  74896. impostor.beforeStep();
  74897. });
  74898. this.world.step();
  74899. impostors.forEach(function (impostor) {
  74900. impostor.afterStep();
  74901. //update the ordered impostors array
  74902. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  74903. });
  74904. //check for collisions
  74905. var contact = this.world.contacts;
  74906. while (contact !== null) {
  74907. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  74908. contact = contact.next;
  74909. continue;
  74910. }
  74911. //is this body colliding with any other? get the impostor
  74912. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  74913. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  74914. if (!mainImpostor || !collidingImpostor) {
  74915. contact = contact.next;
  74916. continue;
  74917. }
  74918. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  74919. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  74920. contact = contact.next;
  74921. }
  74922. };
  74923. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74924. var mass = impostor.physicsBody.massInfo.mass;
  74925. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  74926. };
  74927. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74928. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  74929. this.applyImpulse(impostor, force, contactPoint);
  74930. };
  74931. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74932. var _this = this;
  74933. //parent-child relationship. Does this impostor has a parent impostor?
  74934. if (impostor.parent) {
  74935. if (impostor.physicsBody) {
  74936. this.removePhysicsBody(impostor);
  74937. //TODO is that needed?
  74938. impostor.forceUpdate();
  74939. }
  74940. return;
  74941. }
  74942. if (impostor.isBodyInitRequired()) {
  74943. var bodyConfig = {
  74944. name: impostor.uniqueId,
  74945. //Oimo must have mass, also for static objects.
  74946. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  74947. size: [],
  74948. type: [],
  74949. pos: [],
  74950. rot: [],
  74951. move: impostor.getParam("mass") !== 0,
  74952. //Supporting older versions of Oimo
  74953. world: this.world
  74954. };
  74955. var impostors = [impostor];
  74956. var addToArray = function (parent) {
  74957. if (!parent.getChildMeshes)
  74958. return;
  74959. parent.getChildMeshes().forEach(function (m) {
  74960. if (m.physicsImpostor) {
  74961. impostors.push(m.physicsImpostor);
  74962. //m.physicsImpostor._init();
  74963. }
  74964. });
  74965. };
  74966. addToArray(impostor.object);
  74967. var checkWithEpsilon_1 = function (value) {
  74968. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  74969. };
  74970. impostors.forEach(function (i) {
  74971. if (!impostor.object.rotationQuaternion) {
  74972. return;
  74973. }
  74974. //get the correct bounding box
  74975. var oldQuaternion = i.object.rotationQuaternion;
  74976. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  74977. x: impostor.object.rotationQuaternion.x,
  74978. y: impostor.object.rotationQuaternion.y,
  74979. z: impostor.object.rotationQuaternion.z,
  74980. s: impostor.object.rotationQuaternion.w
  74981. });
  74982. var extendSize = i.getObjectExtendSize();
  74983. if (i === impostor) {
  74984. var center = impostor.getObjectCenter();
  74985. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  74986. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  74987. //Can also use Array.prototype.push.apply
  74988. bodyConfig.pos.push(center.x);
  74989. bodyConfig.pos.push(center.y);
  74990. bodyConfig.pos.push(center.z);
  74991. //tmp solution
  74992. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74993. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74994. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74995. }
  74996. else {
  74997. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  74998. bodyConfig.pos.push(localPosition.x);
  74999. bodyConfig.pos.push(localPosition.y);
  75000. bodyConfig.pos.push(localPosition.z);
  75001. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75002. bodyConfig.rot.push(0);
  75003. bodyConfig.rot.push(0);
  75004. bodyConfig.rot.push(0);
  75005. }
  75006. // register mesh
  75007. switch (i.type) {
  75008. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75009. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75010. case BABYLON.PhysicsImpostor.SphereImpostor:
  75011. var radiusX = extendSize.x;
  75012. var radiusY = extendSize.y;
  75013. var radiusZ = extendSize.z;
  75014. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75015. bodyConfig.type.push('sphere');
  75016. //due to the way oimo works with compounds, add 3 times
  75017. bodyConfig.size.push(size);
  75018. bodyConfig.size.push(size);
  75019. bodyConfig.size.push(size);
  75020. break;
  75021. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75022. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75023. var sizeY = checkWithEpsilon_1(extendSize.y);
  75024. bodyConfig.type.push('cylinder');
  75025. bodyConfig.size.push(sizeX);
  75026. bodyConfig.size.push(sizeY);
  75027. //due to the way oimo works with compounds, add one more value.
  75028. bodyConfig.size.push(sizeY);
  75029. break;
  75030. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75031. case BABYLON.PhysicsImpostor.BoxImpostor:
  75032. default:
  75033. var sizeX = checkWithEpsilon_1(extendSize.x);
  75034. var sizeY = checkWithEpsilon_1(extendSize.y);
  75035. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75036. bodyConfig.type.push('box');
  75037. bodyConfig.size.push(sizeX);
  75038. bodyConfig.size.push(sizeY);
  75039. bodyConfig.size.push(sizeZ);
  75040. break;
  75041. }
  75042. //actually not needed, but hey...
  75043. i.object.rotationQuaternion = oldQuaternion;
  75044. });
  75045. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75046. }
  75047. else {
  75048. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75049. }
  75050. impostor.setDeltaPosition(this._tmpPositionVector);
  75051. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75052. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75053. };
  75054. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75055. //impostor.physicsBody.dispose();
  75056. //Same as : (older oimo versions)
  75057. this.world.removeRigidBody(impostor.physicsBody);
  75058. };
  75059. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75060. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75061. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75062. if (!mainBody || !connectedBody) {
  75063. return;
  75064. }
  75065. var jointData = impostorJoint.joint.jointData;
  75066. var options = jointData.nativeParams || {};
  75067. var type;
  75068. var nativeJointData = {
  75069. body1: mainBody,
  75070. body2: connectedBody,
  75071. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75072. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75073. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75074. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75075. min: options.min,
  75076. max: options.max,
  75077. collision: options.collision || jointData.collision,
  75078. spring: options.spring,
  75079. //supporting older version of Oimo
  75080. world: this.world
  75081. };
  75082. switch (impostorJoint.joint.type) {
  75083. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75084. type = "jointBall";
  75085. break;
  75086. case BABYLON.PhysicsJoint.SpringJoint:
  75087. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75088. var springData = jointData;
  75089. nativeJointData.min = springData.length || nativeJointData.min;
  75090. //Max should also be set, just make sure it is at least min
  75091. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75092. case BABYLON.PhysicsJoint.DistanceJoint:
  75093. type = "jointDistance";
  75094. nativeJointData.max = jointData.maxDistance;
  75095. break;
  75096. case BABYLON.PhysicsJoint.PrismaticJoint:
  75097. type = "jointPrisme";
  75098. break;
  75099. case BABYLON.PhysicsJoint.SliderJoint:
  75100. type = "jointSlide";
  75101. break;
  75102. case BABYLON.PhysicsJoint.WheelJoint:
  75103. type = "jointWheel";
  75104. break;
  75105. case BABYLON.PhysicsJoint.HingeJoint:
  75106. default:
  75107. type = "jointHinge";
  75108. break;
  75109. }
  75110. nativeJointData.type = type;
  75111. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75112. };
  75113. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75114. //Bug in Oimo prevents us from disposing a joint in the playground
  75115. //joint.joint.physicsJoint.dispose();
  75116. //So we will bruteforce it!
  75117. try {
  75118. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75119. }
  75120. catch (e) {
  75121. BABYLON.Tools.Warn(e);
  75122. }
  75123. };
  75124. OimoJSPlugin.prototype.isSupported = function () {
  75125. return this.BJSOIMO !== undefined;
  75126. };
  75127. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75128. if (!impostor.physicsBody.sleeping) {
  75129. //TODO check that
  75130. if (impostor.physicsBody.shapes.next) {
  75131. var parentShape = this._getLastShape(impostor.physicsBody);
  75132. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75133. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75134. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75135. }
  75136. else {
  75137. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75138. }
  75139. if (impostor.object.rotationQuaternion) {
  75140. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75141. impostor.object.rotationQuaternion.normalize();
  75142. }
  75143. }
  75144. };
  75145. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75146. var body = impostor.physicsBody;
  75147. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75148. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75149. body.syncShapes();
  75150. body.awake();
  75151. };
  75152. OimoJSPlugin.prototype._getLastShape = function (body) {
  75153. var lastShape = body.shapes;
  75154. while (lastShape.next) {
  75155. lastShape = lastShape.next;
  75156. }
  75157. return lastShape;
  75158. };
  75159. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75160. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75161. };
  75162. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75163. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75164. };
  75165. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75166. var v = impostor.physicsBody.linearVelocity;
  75167. if (!v) {
  75168. return null;
  75169. }
  75170. return new BABYLON.Vector3(v.x, v.y, v.z);
  75171. };
  75172. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75173. var v = impostor.physicsBody.angularVelocity;
  75174. if (!v) {
  75175. return null;
  75176. }
  75177. return new BABYLON.Vector3(v.x, v.y, v.z);
  75178. };
  75179. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75180. var staticBody = mass === 0;
  75181. //this will actually set the body's density and not its mass.
  75182. //But this is how oimo treats the mass variable.
  75183. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75184. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75185. };
  75186. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75187. return impostor.physicsBody.shapes.density;
  75188. };
  75189. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75190. return impostor.physicsBody.shapes.friction;
  75191. };
  75192. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75193. impostor.physicsBody.shapes.friction = friction;
  75194. };
  75195. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75196. return impostor.physicsBody.shapes.restitution;
  75197. };
  75198. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75199. impostor.physicsBody.shapes.restitution = restitution;
  75200. };
  75201. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75202. impostor.physicsBody.sleep();
  75203. };
  75204. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75205. impostor.physicsBody.awake();
  75206. };
  75207. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75208. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75209. if (minDistance !== void 0) {
  75210. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75211. }
  75212. };
  75213. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75214. //TODO separate rotational and transational motors.
  75215. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75216. if (motor) {
  75217. motor.setMotor(speed, maxForce);
  75218. }
  75219. };
  75220. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75221. //TODO separate rotational and transational motors.
  75222. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75223. if (motor) {
  75224. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75225. }
  75226. };
  75227. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75228. var body = impostor.physicsBody;
  75229. mesh.position.x = body.position.x;
  75230. mesh.position.y = body.position.y;
  75231. mesh.position.z = body.position.z;
  75232. if (mesh.rotationQuaternion) {
  75233. mesh.rotationQuaternion.x = body.orientation.x;
  75234. mesh.rotationQuaternion.y = body.orientation.y;
  75235. mesh.rotationQuaternion.z = body.orientation.z;
  75236. mesh.rotationQuaternion.w = body.orientation.s;
  75237. }
  75238. };
  75239. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75240. return impostor.physicsBody.shapes.radius;
  75241. };
  75242. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75243. var shape = impostor.physicsBody.shapes;
  75244. result.x = shape.halfWidth * 2;
  75245. result.y = shape.halfHeight * 2;
  75246. result.z = shape.halfDepth * 2;
  75247. };
  75248. OimoJSPlugin.prototype.dispose = function () {
  75249. this.world.clear();
  75250. };
  75251. return OimoJSPlugin;
  75252. }());
  75253. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75254. })(BABYLON || (BABYLON = {}));
  75255. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75256. var BABYLON;
  75257. (function (BABYLON) {
  75258. /*
  75259. * Based on jsTGALoader - Javascript loader for TGA file
  75260. * By Vincent Thibault
  75261. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75262. */
  75263. var TGATools = /** @class */ (function () {
  75264. function TGATools() {
  75265. }
  75266. TGATools.GetTGAHeader = function (data) {
  75267. var offset = 0;
  75268. var header = {
  75269. id_length: data[offset++],
  75270. colormap_type: data[offset++],
  75271. image_type: data[offset++],
  75272. colormap_index: data[offset++] | data[offset++] << 8,
  75273. colormap_length: data[offset++] | data[offset++] << 8,
  75274. colormap_size: data[offset++],
  75275. origin: [
  75276. data[offset++] | data[offset++] << 8,
  75277. data[offset++] | data[offset++] << 8
  75278. ],
  75279. width: data[offset++] | data[offset++] << 8,
  75280. height: data[offset++] | data[offset++] << 8,
  75281. pixel_size: data[offset++],
  75282. flags: data[offset++]
  75283. };
  75284. return header;
  75285. };
  75286. TGATools.UploadContent = function (gl, data) {
  75287. // Not enough data to contain header ?
  75288. if (data.length < 19) {
  75289. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75290. return;
  75291. }
  75292. // Read Header
  75293. var offset = 18;
  75294. var header = TGATools.GetTGAHeader(data);
  75295. // Assume it's a valid Targa file.
  75296. if (header.id_length + offset > data.length) {
  75297. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75298. return;
  75299. }
  75300. // Skip not needed data
  75301. offset += header.id_length;
  75302. var use_rle = false;
  75303. var use_pal = false;
  75304. var use_grey = false;
  75305. // Get some informations.
  75306. switch (header.image_type) {
  75307. case TGATools._TYPE_RLE_INDEXED:
  75308. use_rle = true;
  75309. case TGATools._TYPE_INDEXED:
  75310. use_pal = true;
  75311. break;
  75312. case TGATools._TYPE_RLE_RGB:
  75313. use_rle = true;
  75314. case TGATools._TYPE_RGB:
  75315. // use_rgb = true;
  75316. break;
  75317. case TGATools._TYPE_RLE_GREY:
  75318. use_rle = true;
  75319. case TGATools._TYPE_GREY:
  75320. use_grey = true;
  75321. break;
  75322. }
  75323. var pixel_data;
  75324. // var numAlphaBits = header.flags & 0xf;
  75325. var pixel_size = header.pixel_size >> 3;
  75326. var pixel_total = header.width * header.height * pixel_size;
  75327. // Read palettes
  75328. var palettes;
  75329. if (use_pal) {
  75330. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75331. }
  75332. // Read LRE
  75333. if (use_rle) {
  75334. pixel_data = new Uint8Array(pixel_total);
  75335. var c, count, i;
  75336. var localOffset = 0;
  75337. var pixels = new Uint8Array(pixel_size);
  75338. while (offset < pixel_total && localOffset < pixel_total) {
  75339. c = data[offset++];
  75340. count = (c & 0x7f) + 1;
  75341. // RLE pixels
  75342. if (c & 0x80) {
  75343. // Bind pixel tmp array
  75344. for (i = 0; i < pixel_size; ++i) {
  75345. pixels[i] = data[offset++];
  75346. }
  75347. // Copy pixel array
  75348. for (i = 0; i < count; ++i) {
  75349. pixel_data.set(pixels, localOffset + i * pixel_size);
  75350. }
  75351. localOffset += pixel_size * count;
  75352. }
  75353. else {
  75354. count *= pixel_size;
  75355. for (i = 0; i < count; ++i) {
  75356. pixel_data[localOffset + i] = data[offset++];
  75357. }
  75358. localOffset += count;
  75359. }
  75360. }
  75361. }
  75362. else {
  75363. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75364. }
  75365. // Load to texture
  75366. var x_start, y_start, x_step, y_step, y_end, x_end;
  75367. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75368. default:
  75369. case TGATools._ORIGIN_UL:
  75370. x_start = 0;
  75371. x_step = 1;
  75372. x_end = header.width;
  75373. y_start = 0;
  75374. y_step = 1;
  75375. y_end = header.height;
  75376. break;
  75377. case TGATools._ORIGIN_BL:
  75378. x_start = 0;
  75379. x_step = 1;
  75380. x_end = header.width;
  75381. y_start = header.height - 1;
  75382. y_step = -1;
  75383. y_end = -1;
  75384. break;
  75385. case TGATools._ORIGIN_UR:
  75386. x_start = header.width - 1;
  75387. x_step = -1;
  75388. x_end = -1;
  75389. y_start = 0;
  75390. y_step = 1;
  75391. y_end = header.height;
  75392. break;
  75393. case TGATools._ORIGIN_BR:
  75394. x_start = header.width - 1;
  75395. x_step = -1;
  75396. x_end = -1;
  75397. y_start = header.height - 1;
  75398. y_step = -1;
  75399. y_end = -1;
  75400. break;
  75401. }
  75402. // Load the specify method
  75403. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75404. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75405. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75406. };
  75407. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75408. var image = pixel_data, colormap = palettes;
  75409. var width = header.width, height = header.height;
  75410. var color, i = 0, x, y;
  75411. var imageData = new Uint8Array(width * height * 4);
  75412. for (y = y_start; y !== y_end; y += y_step) {
  75413. for (x = x_start; x !== x_end; x += x_step, i++) {
  75414. color = image[i];
  75415. imageData[(x + width * y) * 4 + 3] = 255;
  75416. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75417. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75418. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75419. }
  75420. }
  75421. return imageData;
  75422. };
  75423. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75424. var image = pixel_data;
  75425. var width = header.width, height = header.height;
  75426. var color, i = 0, x, y;
  75427. var imageData = new Uint8Array(width * height * 4);
  75428. for (y = y_start; y !== y_end; y += y_step) {
  75429. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75430. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75431. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75432. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75433. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75434. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75435. }
  75436. }
  75437. return imageData;
  75438. };
  75439. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75440. var image = pixel_data;
  75441. var width = header.width, height = header.height;
  75442. var i = 0, x, y;
  75443. var imageData = new Uint8Array(width * height * 4);
  75444. for (y = y_start; y !== y_end; y += y_step) {
  75445. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75446. imageData[(x + width * y) * 4 + 3] = 255;
  75447. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75448. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75449. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75450. }
  75451. }
  75452. return imageData;
  75453. };
  75454. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75455. var image = pixel_data;
  75456. var width = header.width, height = header.height;
  75457. var i = 0, x, y;
  75458. var imageData = new Uint8Array(width * height * 4);
  75459. for (y = y_start; y !== y_end; y += y_step) {
  75460. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75461. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75462. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75463. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75464. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75465. }
  75466. }
  75467. return imageData;
  75468. };
  75469. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75470. var image = pixel_data;
  75471. var width = header.width, height = header.height;
  75472. var color, i = 0, x, y;
  75473. var imageData = new Uint8Array(width * height * 4);
  75474. for (y = y_start; y !== y_end; y += y_step) {
  75475. for (x = x_start; x !== x_end; x += x_step, i++) {
  75476. color = image[i];
  75477. imageData[(x + width * y) * 4 + 0] = color;
  75478. imageData[(x + width * y) * 4 + 1] = color;
  75479. imageData[(x + width * y) * 4 + 2] = color;
  75480. imageData[(x + width * y) * 4 + 3] = 255;
  75481. }
  75482. }
  75483. return imageData;
  75484. };
  75485. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75486. var image = pixel_data;
  75487. var width = header.width, height = header.height;
  75488. var i = 0, x, y;
  75489. var imageData = new Uint8Array(width * height * 4);
  75490. for (y = y_start; y !== y_end; y += y_step) {
  75491. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75492. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75493. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75494. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75495. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75496. }
  75497. }
  75498. return imageData;
  75499. };
  75500. //private static _TYPE_NO_DATA = 0;
  75501. TGATools._TYPE_INDEXED = 1;
  75502. TGATools._TYPE_RGB = 2;
  75503. TGATools._TYPE_GREY = 3;
  75504. TGATools._TYPE_RLE_INDEXED = 9;
  75505. TGATools._TYPE_RLE_RGB = 10;
  75506. TGATools._TYPE_RLE_GREY = 11;
  75507. TGATools._ORIGIN_MASK = 0x30;
  75508. TGATools._ORIGIN_SHIFT = 0x04;
  75509. TGATools._ORIGIN_BL = 0x00;
  75510. TGATools._ORIGIN_BR = 0x01;
  75511. TGATools._ORIGIN_UL = 0x02;
  75512. TGATools._ORIGIN_UR = 0x03;
  75513. return TGATools;
  75514. }());
  75515. BABYLON.TGATools = TGATools;
  75516. })(BABYLON || (BABYLON = {}));
  75517. //# sourceMappingURL=babylon.tga.js.map
  75518. var BABYLON;
  75519. (function (BABYLON) {
  75520. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75521. // All values and structures referenced from:
  75522. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75523. var DDS_MAGIC = 0x20534444;
  75524. var
  75525. //DDSD_CAPS = 0x1,
  75526. //DDSD_HEIGHT = 0x2,
  75527. //DDSD_WIDTH = 0x4,
  75528. //DDSD_PITCH = 0x8,
  75529. //DDSD_PIXELFORMAT = 0x1000,
  75530. DDSD_MIPMAPCOUNT = 0x20000;
  75531. //DDSD_LINEARSIZE = 0x80000,
  75532. //DDSD_DEPTH = 0x800000;
  75533. // var DDSCAPS_COMPLEX = 0x8,
  75534. // DDSCAPS_MIPMAP = 0x400000,
  75535. // DDSCAPS_TEXTURE = 0x1000;
  75536. var DDSCAPS2_CUBEMAP = 0x200;
  75537. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75538. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75539. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75540. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75541. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75542. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75543. // DDSCAPS2_VOLUME = 0x200000;
  75544. var
  75545. //DDPF_ALPHAPIXELS = 0x1,
  75546. //DDPF_ALPHA = 0x2,
  75547. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75548. //DDPF_YUV = 0x200,
  75549. DDPF_LUMINANCE = 0x20000;
  75550. function FourCCToInt32(value) {
  75551. return value.charCodeAt(0) +
  75552. (value.charCodeAt(1) << 8) +
  75553. (value.charCodeAt(2) << 16) +
  75554. (value.charCodeAt(3) << 24);
  75555. }
  75556. function Int32ToFourCC(value) {
  75557. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75558. }
  75559. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75560. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75561. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75562. var FOURCC_DX10 = FourCCToInt32("DX10");
  75563. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75564. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75565. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75566. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75567. var headerLengthInt = 31; // The header length in 32 bit ints
  75568. // Offsets into the header array
  75569. var off_magic = 0;
  75570. var off_size = 1;
  75571. var off_flags = 2;
  75572. var off_height = 3;
  75573. var off_width = 4;
  75574. var off_mipmapCount = 7;
  75575. var off_pfFlags = 20;
  75576. var off_pfFourCC = 21;
  75577. var off_RGBbpp = 22;
  75578. var off_RMask = 23;
  75579. var off_GMask = 24;
  75580. var off_BMask = 25;
  75581. var off_AMask = 26;
  75582. // var off_caps1 = 27;
  75583. var off_caps2 = 28;
  75584. // var off_caps3 = 29;
  75585. // var off_caps4 = 30;
  75586. var off_dxgiFormat = 32;
  75587. ;
  75588. var DDSTools = /** @class */ (function () {
  75589. function DDSTools() {
  75590. }
  75591. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75592. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75593. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75594. var mipmapCount = 1;
  75595. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75596. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75597. }
  75598. var fourCC = header[off_pfFourCC];
  75599. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75600. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75601. switch (fourCC) {
  75602. case FOURCC_D3DFMT_R16G16B16A16F:
  75603. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75604. break;
  75605. case FOURCC_D3DFMT_R32G32B32A32F:
  75606. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75607. break;
  75608. case FOURCC_DX10:
  75609. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75610. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75611. break;
  75612. }
  75613. }
  75614. return {
  75615. width: header[off_width],
  75616. height: header[off_height],
  75617. mipmapCount: mipmapCount,
  75618. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75619. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75620. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75621. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75622. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75623. dxgiFormat: dxgiFormat,
  75624. textureType: textureType
  75625. };
  75626. };
  75627. DDSTools._ToHalfFloat = function (value) {
  75628. if (!DDSTools._FloatView) {
  75629. DDSTools._FloatView = new Float32Array(1);
  75630. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75631. }
  75632. DDSTools._FloatView[0] = value;
  75633. var x = DDSTools._Int32View[0];
  75634. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75635. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75636. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75637. /* If zero, or denormal, or exponent underflows too much for a denormal
  75638. * half, return signed zero. */
  75639. if (e < 103) {
  75640. return bits;
  75641. }
  75642. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75643. if (e > 142) {
  75644. bits |= 0x7c00;
  75645. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75646. * not Inf, so make sure we set one mantissa bit too. */
  75647. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75648. return bits;
  75649. }
  75650. /* If exponent underflows but not too much, return a denormal */
  75651. if (e < 113) {
  75652. m |= 0x0800;
  75653. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75654. * to 1, which is OK. */
  75655. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75656. return bits;
  75657. }
  75658. bits |= ((e - 112) << 10) | (m >> 1);
  75659. bits += m & 1;
  75660. return bits;
  75661. };
  75662. DDSTools._FromHalfFloat = function (value) {
  75663. var s = (value & 0x8000) >> 15;
  75664. var e = (value & 0x7C00) >> 10;
  75665. var f = value & 0x03FF;
  75666. if (e === 0) {
  75667. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75668. }
  75669. else if (e == 0x1F) {
  75670. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75671. }
  75672. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75673. };
  75674. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75675. var destArray = new Float32Array(dataLength);
  75676. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75677. var index = 0;
  75678. for (var y = 0; y < height; y++) {
  75679. for (var x = 0; x < width; x++) {
  75680. var srcPos = (x + y * width) * 4;
  75681. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75682. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75683. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75684. if (DDSTools.StoreLODInAlphaChannel) {
  75685. destArray[index + 3] = lod;
  75686. }
  75687. else {
  75688. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75689. }
  75690. index += 4;
  75691. }
  75692. }
  75693. return destArray;
  75694. };
  75695. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75696. if (DDSTools.StoreLODInAlphaChannel) {
  75697. var destArray = new Uint16Array(dataLength);
  75698. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75699. var index = 0;
  75700. for (var y = 0; y < height; y++) {
  75701. for (var x = 0; x < width; x++) {
  75702. var srcPos = (x + y * width) * 4;
  75703. destArray[index] = srcData[srcPos];
  75704. destArray[index + 1] = srcData[srcPos + 1];
  75705. destArray[index + 2] = srcData[srcPos + 2];
  75706. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75707. index += 4;
  75708. }
  75709. }
  75710. return destArray;
  75711. }
  75712. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75713. };
  75714. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75715. if (DDSTools.StoreLODInAlphaChannel) {
  75716. var destArray = new Float32Array(dataLength);
  75717. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75718. var index = 0;
  75719. for (var y = 0; y < height; y++) {
  75720. for (var x = 0; x < width; x++) {
  75721. var srcPos = (x + y * width) * 4;
  75722. destArray[index] = srcData[srcPos];
  75723. destArray[index + 1] = srcData[srcPos + 1];
  75724. destArray[index + 2] = srcData[srcPos + 2];
  75725. destArray[index + 3] = lod;
  75726. index += 4;
  75727. }
  75728. }
  75729. return destArray;
  75730. }
  75731. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75732. };
  75733. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75734. var destArray = new Uint8Array(dataLength);
  75735. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75736. var index = 0;
  75737. for (var y = 0; y < height; y++) {
  75738. for (var x = 0; x < width; x++) {
  75739. var srcPos = (x + y * width) * 4;
  75740. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75741. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75742. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75743. if (DDSTools.StoreLODInAlphaChannel) {
  75744. destArray[index + 3] = lod;
  75745. }
  75746. else {
  75747. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75748. }
  75749. index += 4;
  75750. }
  75751. }
  75752. return destArray;
  75753. };
  75754. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75755. var destArray = new Uint8Array(dataLength);
  75756. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75757. var index = 0;
  75758. for (var y = 0; y < height; y++) {
  75759. for (var x = 0; x < width; x++) {
  75760. var srcPos = (x + y * width) * 4;
  75761. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75762. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75763. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75764. if (DDSTools.StoreLODInAlphaChannel) {
  75765. destArray[index + 3] = lod;
  75766. }
  75767. else {
  75768. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75769. }
  75770. index += 4;
  75771. }
  75772. }
  75773. return destArray;
  75774. };
  75775. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75776. var byteArray = new Uint8Array(dataLength);
  75777. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75778. var index = 0;
  75779. for (var y = 0; y < height; y++) {
  75780. for (var x = 0; x < width; x++) {
  75781. var srcPos = (x + y * width) * 4;
  75782. byteArray[index] = srcData[srcPos + rOffset];
  75783. byteArray[index + 1] = srcData[srcPos + gOffset];
  75784. byteArray[index + 2] = srcData[srcPos + bOffset];
  75785. byteArray[index + 3] = srcData[srcPos + aOffset];
  75786. index += 4;
  75787. }
  75788. }
  75789. return byteArray;
  75790. };
  75791. DDSTools._ExtractLongWordOrder = function (value) {
  75792. if (value === 0 || value === 255 || value === -16777216) {
  75793. return 0;
  75794. }
  75795. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75796. };
  75797. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75798. var byteArray = new Uint8Array(dataLength);
  75799. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75800. var index = 0;
  75801. for (var y = 0; y < height; y++) {
  75802. for (var x = 0; x < width; x++) {
  75803. var srcPos = (x + y * width) * 3;
  75804. byteArray[index] = srcData[srcPos + rOffset];
  75805. byteArray[index + 1] = srcData[srcPos + gOffset];
  75806. byteArray[index + 2] = srcData[srcPos + bOffset];
  75807. index += 3;
  75808. }
  75809. }
  75810. return byteArray;
  75811. };
  75812. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75813. var byteArray = new Uint8Array(dataLength);
  75814. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75815. var index = 0;
  75816. for (var y = 0; y < height; y++) {
  75817. for (var x = 0; x < width; x++) {
  75818. var srcPos = (x + y * width);
  75819. byteArray[index] = srcData[srcPos];
  75820. index++;
  75821. }
  75822. }
  75823. return byteArray;
  75824. };
  75825. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75826. if (lodIndex === void 0) { lodIndex = -1; }
  75827. var ext = engine.getCaps().s3tc;
  75828. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75829. var fourCC, width, height, dataLength = 0, dataOffset;
  75830. var byteArray, mipmapCount, mip;
  75831. var internalFormat = 0;
  75832. var format = 0;
  75833. var blockBytes = 1;
  75834. if (header[off_magic] !== DDS_MAGIC) {
  75835. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75836. return;
  75837. }
  75838. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75839. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75840. return;
  75841. }
  75842. if (info.isCompressed && !ext) {
  75843. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75844. return;
  75845. }
  75846. var bpp = header[off_RGBbpp];
  75847. dataOffset = header[off_size] + 4;
  75848. var computeFormats = false;
  75849. if (info.isFourCC) {
  75850. fourCC = header[off_pfFourCC];
  75851. switch (fourCC) {
  75852. case FOURCC_DXT1:
  75853. blockBytes = 8;
  75854. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75855. break;
  75856. case FOURCC_DXT3:
  75857. blockBytes = 16;
  75858. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75859. break;
  75860. case FOURCC_DXT5:
  75861. blockBytes = 16;
  75862. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75863. break;
  75864. case FOURCC_D3DFMT_R16G16B16A16F:
  75865. computeFormats = true;
  75866. break;
  75867. case FOURCC_D3DFMT_R32G32B32A32F:
  75868. computeFormats = true;
  75869. break;
  75870. case FOURCC_DX10:
  75871. // There is an additionnal header so dataOffset need to be changed
  75872. dataOffset += 5 * 4; // 5 uints
  75873. var supported = false;
  75874. switch (info.dxgiFormat) {
  75875. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  75876. computeFormats = true;
  75877. supported = true;
  75878. break;
  75879. case DXGI_FORMAT_B8G8R8X8_UNORM:
  75880. info.isRGB = true;
  75881. info.isFourCC = false;
  75882. bpp = 32;
  75883. supported = true;
  75884. break;
  75885. }
  75886. if (supported) {
  75887. break;
  75888. }
  75889. default:
  75890. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  75891. return;
  75892. }
  75893. }
  75894. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  75895. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  75896. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  75897. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  75898. if (computeFormats) {
  75899. format = engine._getWebGLTextureType(info.textureType);
  75900. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75901. }
  75902. mipmapCount = 1;
  75903. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  75904. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75905. }
  75906. for (var face = 0; face < faces; face++) {
  75907. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  75908. width = header[off_width];
  75909. height = header[off_height];
  75910. for (mip = 0; mip < mipmapCount; ++mip) {
  75911. if (lodIndex === -1 || lodIndex === mip) {
  75912. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  75913. var i = (lodIndex === -1) ? mip : 0;
  75914. if (!info.isCompressed && info.isFourCC) {
  75915. dataLength = width * height * 4;
  75916. var floatArray = null;
  75917. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  75918. if (bpp === 128) {
  75919. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75920. }
  75921. else if (bpp === 64) {
  75922. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75923. }
  75924. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75925. format = engine._getWebGLTextureType(info.textureType);
  75926. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75927. }
  75928. else {
  75929. if (bpp === 128) {
  75930. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75931. }
  75932. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  75933. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75934. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75935. format = engine._getWebGLTextureType(info.textureType);
  75936. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75937. }
  75938. else {
  75939. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75940. }
  75941. }
  75942. if (floatArray) {
  75943. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  75944. }
  75945. }
  75946. else if (info.isRGB) {
  75947. if (bpp === 24) {
  75948. dataLength = width * height * 3;
  75949. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  75950. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  75951. }
  75952. else {
  75953. dataLength = width * height * 4;
  75954. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  75955. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  75956. }
  75957. }
  75958. else if (info.isLuminance) {
  75959. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  75960. var unpaddedRowSize = width;
  75961. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  75962. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  75963. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  75964. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  75965. }
  75966. else {
  75967. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  75968. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  75969. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  75970. }
  75971. }
  75972. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  75973. width *= 0.5;
  75974. height *= 0.5;
  75975. width = Math.max(1.0, width);
  75976. height = Math.max(1.0, height);
  75977. }
  75978. if (currentFace !== undefined) {
  75979. // Loading a single face
  75980. break;
  75981. }
  75982. }
  75983. };
  75984. DDSTools.StoreLODInAlphaChannel = false;
  75985. return DDSTools;
  75986. }());
  75987. BABYLON.DDSTools = DDSTools;
  75988. })(BABYLON || (BABYLON = {}));
  75989. //# sourceMappingURL=babylon.dds.js.map
  75990. var BABYLON;
  75991. (function (BABYLON) {
  75992. /**
  75993. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  75994. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  75995. */
  75996. var KhronosTextureContainer = /** @class */ (function () {
  75997. /**
  75998. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  75999. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76000. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76001. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76002. */
  76003. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76004. this.arrayBuffer = arrayBuffer;
  76005. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76006. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76007. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76008. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76009. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76010. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76011. BABYLON.Tools.Error("texture missing KTX identifier");
  76012. return;
  76013. }
  76014. // load the reset of the header in native 32 bit int
  76015. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76016. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76017. var oppositeEndianess = header[0] === 0x01020304;
  76018. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76019. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76020. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76021. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76022. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76023. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76024. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76025. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76026. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76027. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76028. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76029. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76030. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76031. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76032. if (this.glType !== 0) {
  76033. BABYLON.Tools.Error("only compressed formats currently supported");
  76034. return;
  76035. }
  76036. else {
  76037. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76038. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76039. }
  76040. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76041. BABYLON.Tools.Error("only 2D textures currently supported");
  76042. return;
  76043. }
  76044. if (this.numberOfArrayElements !== 0) {
  76045. BABYLON.Tools.Error("texture arrays not currently supported");
  76046. return;
  76047. }
  76048. if (this.numberOfFaces !== facesExpected) {
  76049. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76050. return;
  76051. }
  76052. // we now have a completely validated file, so could use existence of loadType as success
  76053. // would need to make this more elaborate & adjust checks above to support more than one load type
  76054. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76055. }
  76056. // not as fast hardware based, but will probably never need to use
  76057. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76058. return ((val & 0xFF) << 24)
  76059. | ((val & 0xFF00) << 8)
  76060. | ((val >> 8) & 0xFF00)
  76061. | ((val >> 24) & 0xFF);
  76062. };
  76063. /**
  76064. * It is assumed that the texture has already been created & is currently bound
  76065. */
  76066. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76067. switch (this.loadType) {
  76068. case KhronosTextureContainer.COMPRESSED_2D:
  76069. this._upload2DCompressedLevels(gl, loadMipmaps);
  76070. break;
  76071. case KhronosTextureContainer.TEX_2D:
  76072. case KhronosTextureContainer.COMPRESSED_3D:
  76073. case KhronosTextureContainer.TEX_3D:
  76074. }
  76075. };
  76076. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76077. // initialize width & height for level 1
  76078. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76079. var width = this.pixelWidth;
  76080. var height = this.pixelHeight;
  76081. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76082. for (var level = 0; level < mipmapCount; level++) {
  76083. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76084. for (var face = 0; face < this.numberOfFaces; face++) {
  76085. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76086. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76087. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76088. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76089. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76090. }
  76091. width = Math.max(1.0, width * 0.5);
  76092. height = Math.max(1.0, height * 0.5);
  76093. }
  76094. };
  76095. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76096. // load types
  76097. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76098. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76099. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76100. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76101. return KhronosTextureContainer;
  76102. }());
  76103. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76104. })(BABYLON || (BABYLON = {}));
  76105. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76106. var BABYLON;
  76107. (function (BABYLON) {
  76108. var Debug = /** @class */ (function () {
  76109. function Debug() {
  76110. }
  76111. Debug.AxesViewer = /** @class */ (function () {
  76112. function AxesViewer(scene, scaleLines) {
  76113. if (scaleLines === void 0) { scaleLines = 1; }
  76114. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76115. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76116. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76117. this.scaleLines = 1;
  76118. this.scaleLines = scaleLines;
  76119. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76120. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76121. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76122. this._xmesh.renderingGroupId = 2;
  76123. this._ymesh.renderingGroupId = 2;
  76124. this._zmesh.renderingGroupId = 2;
  76125. this._xmesh.material.checkReadyOnlyOnce = true;
  76126. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76127. this._ymesh.material.checkReadyOnlyOnce = true;
  76128. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76129. this._zmesh.material.checkReadyOnlyOnce = true;
  76130. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76131. this.scene = scene;
  76132. }
  76133. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76134. var scaleLines = this.scaleLines;
  76135. if (this._xmesh) {
  76136. this._xmesh.position.copyFrom(position);
  76137. }
  76138. if (this._ymesh) {
  76139. this._ymesh.position.copyFrom(position);
  76140. }
  76141. if (this._zmesh) {
  76142. this._zmesh.position.copyFrom(position);
  76143. }
  76144. var point2 = this._xline[1];
  76145. point2.x = xaxis.x * scaleLines;
  76146. point2.y = xaxis.y * scaleLines;
  76147. point2.z = xaxis.z * scaleLines;
  76148. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76149. point2 = this._yline[1];
  76150. point2.x = yaxis.x * scaleLines;
  76151. point2.y = yaxis.y * scaleLines;
  76152. point2.z = yaxis.z * scaleLines;
  76153. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76154. point2 = this._zline[1];
  76155. point2.x = zaxis.x * scaleLines;
  76156. point2.y = zaxis.y * scaleLines;
  76157. point2.z = zaxis.z * scaleLines;
  76158. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76159. };
  76160. AxesViewer.prototype.dispose = function () {
  76161. if (this._xmesh) {
  76162. this._xmesh.dispose();
  76163. }
  76164. if (this._ymesh) {
  76165. this._ymesh.dispose();
  76166. }
  76167. if (this._zmesh) {
  76168. this._zmesh.dispose();
  76169. }
  76170. this._xmesh = null;
  76171. this._ymesh = null;
  76172. this._zmesh = null;
  76173. this.scene = null;
  76174. };
  76175. return AxesViewer;
  76176. }());
  76177. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76178. __extends(BoneAxesViewer, _super);
  76179. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76180. if (scaleLines === void 0) { scaleLines = 1; }
  76181. var _this = _super.call(this, scene, scaleLines) || this;
  76182. _this.pos = BABYLON.Vector3.Zero();
  76183. _this.xaxis = BABYLON.Vector3.Zero();
  76184. _this.yaxis = BABYLON.Vector3.Zero();
  76185. _this.zaxis = BABYLON.Vector3.Zero();
  76186. _this.mesh = mesh;
  76187. _this.bone = bone;
  76188. return _this;
  76189. }
  76190. BoneAxesViewer.prototype.update = function () {
  76191. if (!this.mesh || !this.bone) {
  76192. return;
  76193. }
  76194. var bone = this.bone;
  76195. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76196. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76197. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76198. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76199. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76200. };
  76201. BoneAxesViewer.prototype.dispose = function () {
  76202. if (this.mesh) {
  76203. this.mesh = null;
  76204. this.bone = null;
  76205. _super.prototype.dispose.call(this);
  76206. }
  76207. };
  76208. return BoneAxesViewer;
  76209. }(Debug.AxesViewer));
  76210. Debug.PhysicsViewer = /** @class */ (function () {
  76211. function PhysicsViewer(scene) {
  76212. this._impostors = [];
  76213. this._meshes = [];
  76214. this._numMeshes = 0;
  76215. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76216. var physicEngine = this._scene.getPhysicsEngine();
  76217. if (physicEngine) {
  76218. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76219. }
  76220. }
  76221. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76222. var plugin = this._physicsEnginePlugin;
  76223. for (var i = 0; i < this._numMeshes; i++) {
  76224. var impostor = this._impostors[i];
  76225. if (!impostor) {
  76226. continue;
  76227. }
  76228. if (impostor.isDisposed) {
  76229. this.hideImpostor(this._impostors[i--]);
  76230. }
  76231. else {
  76232. var mesh = this._meshes[i];
  76233. if (mesh && plugin) {
  76234. plugin.syncMeshWithImpostor(mesh, impostor);
  76235. }
  76236. }
  76237. }
  76238. };
  76239. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76240. if (!this._scene) {
  76241. return;
  76242. }
  76243. for (var i = 0; i < this._numMeshes; i++) {
  76244. if (this._impostors[i] == impostor) {
  76245. return;
  76246. }
  76247. }
  76248. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76249. if (debugMesh) {
  76250. this._impostors[this._numMeshes] = impostor;
  76251. this._meshes[this._numMeshes] = debugMesh;
  76252. if (this._numMeshes === 0) {
  76253. this._renderFunction = this._updateDebugMeshes.bind(this);
  76254. this._scene.registerBeforeRender(this._renderFunction);
  76255. }
  76256. this._numMeshes++;
  76257. }
  76258. };
  76259. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76260. if (!impostor || !this._scene) {
  76261. return;
  76262. }
  76263. var removed = false;
  76264. for (var i = 0; i < this._numMeshes; i++) {
  76265. if (this._impostors[i] == impostor) {
  76266. var mesh = this._meshes[i];
  76267. if (!mesh) {
  76268. continue;
  76269. }
  76270. this._scene.removeMesh(mesh);
  76271. mesh.dispose();
  76272. this._numMeshes--;
  76273. if (this._numMeshes > 0) {
  76274. this._meshes[i] = this._meshes[this._numMeshes];
  76275. this._impostors[i] = this._impostors[this._numMeshes];
  76276. this._meshes[this._numMeshes] = null;
  76277. this._impostors[this._numMeshes] = null;
  76278. }
  76279. else {
  76280. this._meshes[0] = null;
  76281. this._impostors[0] = null;
  76282. }
  76283. removed = true;
  76284. break;
  76285. }
  76286. }
  76287. if (removed && this._numMeshes === 0) {
  76288. this._scene.unregisterBeforeRender(this._renderFunction);
  76289. }
  76290. };
  76291. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76292. if (!this._debugMaterial) {
  76293. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76294. this._debugMaterial.wireframe = true;
  76295. }
  76296. return this._debugMaterial;
  76297. };
  76298. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76299. if (!this._debugBoxMesh) {
  76300. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76301. this._debugBoxMesh.renderingGroupId = 1;
  76302. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76303. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76304. scene.removeMesh(this._debugBoxMesh);
  76305. }
  76306. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76307. };
  76308. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76309. if (!this._debugSphereMesh) {
  76310. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76311. this._debugSphereMesh.renderingGroupId = 1;
  76312. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76313. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76314. scene.removeMesh(this._debugSphereMesh);
  76315. }
  76316. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76317. };
  76318. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76319. var mesh = null;
  76320. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76321. mesh = this._getDebugBoxMesh(scene);
  76322. impostor.getBoxSizeToRef(mesh.scaling);
  76323. }
  76324. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76325. mesh = this._getDebugSphereMesh(scene);
  76326. var radius = impostor.getRadius();
  76327. mesh.scaling.x = radius * 2;
  76328. mesh.scaling.y = radius * 2;
  76329. mesh.scaling.z = radius * 2;
  76330. }
  76331. return mesh;
  76332. };
  76333. PhysicsViewer.prototype.dispose = function () {
  76334. for (var i = 0; i < this._numMeshes; i++) {
  76335. this.hideImpostor(this._impostors[i]);
  76336. }
  76337. if (this._debugBoxMesh) {
  76338. this._debugBoxMesh.dispose();
  76339. }
  76340. if (this._debugSphereMesh) {
  76341. this._debugSphereMesh.dispose();
  76342. }
  76343. if (this._debugMaterial) {
  76344. this._debugMaterial.dispose();
  76345. }
  76346. this._impostors.length = 0;
  76347. this._scene = null;
  76348. this._physicsEnginePlugin = null;
  76349. };
  76350. return PhysicsViewer;
  76351. }());
  76352. Debug.SkeletonViewer = /** @class */ (function () {
  76353. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76354. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76355. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76356. this.skeleton = skeleton;
  76357. this.mesh = mesh;
  76358. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76359. this.renderingGroupId = renderingGroupId;
  76360. this.color = BABYLON.Color3.White();
  76361. this._debugLines = new Array();
  76362. this._isEnabled = false;
  76363. this._scene = scene;
  76364. this.update();
  76365. this._renderFunction = this.update.bind(this);
  76366. }
  76367. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76368. get: function () {
  76369. return this._isEnabled;
  76370. },
  76371. set: function (value) {
  76372. if (this._isEnabled === value) {
  76373. return;
  76374. }
  76375. this._isEnabled = value;
  76376. if (value) {
  76377. this._scene.registerBeforeRender(this._renderFunction);
  76378. }
  76379. else {
  76380. this._scene.unregisterBeforeRender(this._renderFunction);
  76381. }
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76387. if (x === void 0) { x = 0; }
  76388. if (y === void 0) { y = 0; }
  76389. if (z === void 0) { z = 0; }
  76390. var tmat = BABYLON.Tmp.Matrix[0];
  76391. var parentBone = bone.getParent();
  76392. tmat.copyFrom(bone.getLocalMatrix());
  76393. if (x !== 0 || y !== 0 || z !== 0) {
  76394. var tmat2 = BABYLON.Tmp.Matrix[1];
  76395. BABYLON.Matrix.IdentityToRef(tmat2);
  76396. tmat2.m[12] = x;
  76397. tmat2.m[13] = y;
  76398. tmat2.m[14] = z;
  76399. tmat2.multiplyToRef(tmat, tmat);
  76400. }
  76401. if (parentBone) {
  76402. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76403. }
  76404. tmat.multiplyToRef(meshMat, tmat);
  76405. position.x = tmat.m[12];
  76406. position.y = tmat.m[13];
  76407. position.z = tmat.m[14];
  76408. };
  76409. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76410. var len = bones.length;
  76411. var meshPos = this.mesh.position;
  76412. for (var i = 0; i < len; i++) {
  76413. var bone = bones[i];
  76414. var points = this._debugLines[i];
  76415. if (!points) {
  76416. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76417. this._debugLines[i] = points;
  76418. }
  76419. this._getBonePosition(points[0], bone, meshMat);
  76420. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76421. points[0].subtractInPlace(meshPos);
  76422. points[1].subtractInPlace(meshPos);
  76423. }
  76424. };
  76425. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76426. var len = bones.length;
  76427. var boneNum = 0;
  76428. var meshPos = this.mesh.position;
  76429. for (var i = len - 1; i >= 0; i--) {
  76430. var childBone = bones[i];
  76431. var parentBone = childBone.getParent();
  76432. if (!parentBone) {
  76433. continue;
  76434. }
  76435. var points = this._debugLines[boneNum];
  76436. if (!points) {
  76437. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76438. this._debugLines[boneNum] = points;
  76439. }
  76440. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76441. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76442. points[0].subtractInPlace(meshPos);
  76443. points[1].subtractInPlace(meshPos);
  76444. boneNum++;
  76445. }
  76446. };
  76447. SkeletonViewer.prototype.update = function () {
  76448. if (this.autoUpdateBonesMatrices) {
  76449. this.skeleton.computeAbsoluteTransforms();
  76450. }
  76451. if (this.skeleton.bones[0].length === undefined) {
  76452. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76453. }
  76454. else {
  76455. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76456. }
  76457. if (!this._debugMesh) {
  76458. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76459. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76460. }
  76461. else {
  76462. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76463. }
  76464. this._debugMesh.position.copyFrom(this.mesh.position);
  76465. this._debugMesh.color = this.color;
  76466. };
  76467. SkeletonViewer.prototype.dispose = function () {
  76468. if (this._debugMesh) {
  76469. this.isEnabled = false;
  76470. this._debugMesh.dispose();
  76471. this._debugMesh = null;
  76472. }
  76473. };
  76474. return SkeletonViewer;
  76475. }());
  76476. return Debug;
  76477. }());
  76478. BABYLON.Debug = Debug;
  76479. })(BABYLON || (BABYLON = {}));
  76480. //# sourceMappingURL=babylon.debugModules.js.map
  76481. var BABYLON;
  76482. (function (BABYLON) {
  76483. var RayHelper = /** @class */ (function () {
  76484. function RayHelper(ray) {
  76485. this.ray = ray;
  76486. }
  76487. RayHelper.CreateAndShow = function (ray, scene, color) {
  76488. var helper = new RayHelper(ray);
  76489. helper.show(scene, color);
  76490. return helper;
  76491. };
  76492. RayHelper.prototype.show = function (scene, color) {
  76493. if (!this._renderFunction && this.ray) {
  76494. var ray = this.ray;
  76495. this._renderFunction = this._render.bind(this);
  76496. this._scene = scene;
  76497. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76498. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76499. if (this._renderFunction) {
  76500. this._scene.registerBeforeRender(this._renderFunction);
  76501. }
  76502. }
  76503. if (color && this._renderLine) {
  76504. this._renderLine.color.copyFrom(color);
  76505. }
  76506. };
  76507. RayHelper.prototype.hide = function () {
  76508. if (this._renderFunction && this._scene) {
  76509. this._scene.unregisterBeforeRender(this._renderFunction);
  76510. this._scene = null;
  76511. this._renderFunction = null;
  76512. if (this._renderLine) {
  76513. this._renderLine.dispose();
  76514. this._renderLine = null;
  76515. }
  76516. this._renderPoints = [];
  76517. }
  76518. };
  76519. RayHelper.prototype._render = function () {
  76520. var ray = this.ray;
  76521. if (!ray) {
  76522. return;
  76523. }
  76524. var point = this._renderPoints[1];
  76525. var len = Math.min(ray.length, 1000000);
  76526. point.copyFrom(ray.direction);
  76527. point.scaleInPlace(len);
  76528. point.addInPlace(ray.origin);
  76529. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76530. };
  76531. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76532. this._attachedToMesh = mesh;
  76533. var ray = this.ray;
  76534. if (!ray) {
  76535. return;
  76536. }
  76537. if (!ray.direction) {
  76538. ray.direction = BABYLON.Vector3.Zero();
  76539. }
  76540. if (!ray.origin) {
  76541. ray.origin = BABYLON.Vector3.Zero();
  76542. }
  76543. if (length) {
  76544. ray.length = length;
  76545. }
  76546. if (!meshSpaceOrigin) {
  76547. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76548. }
  76549. if (!meshSpaceDirection) {
  76550. // -1 so that this will work with Mesh.lookAt
  76551. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76552. }
  76553. if (!this._meshSpaceDirection) {
  76554. this._meshSpaceDirection = meshSpaceDirection.clone();
  76555. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76556. }
  76557. else {
  76558. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76559. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76560. }
  76561. if (!this._updateToMeshFunction) {
  76562. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76563. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76564. }
  76565. this._updateToMesh();
  76566. };
  76567. RayHelper.prototype.detachFromMesh = function () {
  76568. if (this._attachedToMesh) {
  76569. if (this._updateToMeshFunction) {
  76570. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76571. }
  76572. this._attachedToMesh = null;
  76573. this._updateToMeshFunction = null;
  76574. }
  76575. };
  76576. RayHelper.prototype._updateToMesh = function () {
  76577. var ray = this.ray;
  76578. if (!this._attachedToMesh || !ray) {
  76579. return;
  76580. }
  76581. if (this._attachedToMesh._isDisposed) {
  76582. this.detachFromMesh();
  76583. return;
  76584. }
  76585. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76586. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76587. };
  76588. RayHelper.prototype.dispose = function () {
  76589. this.hide();
  76590. this.detachFromMesh();
  76591. this.ray = null;
  76592. };
  76593. return RayHelper;
  76594. }());
  76595. BABYLON.RayHelper = RayHelper;
  76596. })(BABYLON || (BABYLON = {}));
  76597. //# sourceMappingURL=babylon.rayHelper.js.map
  76598. var BABYLON;
  76599. (function (BABYLON) {
  76600. // load the inspector using require, if not present in the global namespace.
  76601. var DebugLayer = /** @class */ (function () {
  76602. function DebugLayer(scene) {
  76603. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76604. this._scene = scene;
  76605. // load inspector using require, if it doesn't exist on the global namespace.
  76606. }
  76607. /** Creates the inspector window. */
  76608. DebugLayer.prototype._createInspector = function (config) {
  76609. if (config === void 0) { config = {}; }
  76610. var popup = config.popup || false;
  76611. var initialTab = config.initialTab || 0;
  76612. var parentElement = config.parentElement || null;
  76613. if (!this._inspector) {
  76614. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76615. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76616. } // else nothing to do,; instance is already existing
  76617. };
  76618. DebugLayer.prototype.isVisible = function () {
  76619. if (!this._inspector) {
  76620. return false;
  76621. }
  76622. return true;
  76623. };
  76624. DebugLayer.prototype.hide = function () {
  76625. if (this._inspector) {
  76626. try {
  76627. this._inspector.dispose();
  76628. }
  76629. catch (e) {
  76630. // If the inspector has been removed directly from the inspector tool
  76631. }
  76632. this._inspector = null;
  76633. }
  76634. };
  76635. DebugLayer.prototype.show = function (config) {
  76636. if (config === void 0) { config = {}; }
  76637. if (typeof this.BJSINSPECTOR == 'undefined') {
  76638. // Load inspector and add it to the DOM
  76639. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76640. }
  76641. else {
  76642. // Otherwise creates the inspector
  76643. this._createInspector(config);
  76644. }
  76645. };
  76646. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76647. return DebugLayer;
  76648. }());
  76649. BABYLON.DebugLayer = DebugLayer;
  76650. })(BABYLON || (BABYLON = {}));
  76651. //# sourceMappingURL=babylon.debugLayer.js.map
  76652. var BABYLON;
  76653. (function (BABYLON) {
  76654. var BoundingBoxRenderer = /** @class */ (function () {
  76655. function BoundingBoxRenderer(scene) {
  76656. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76657. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76658. this.showBackLines = true;
  76659. this.renderList = new BABYLON.SmartArray(32);
  76660. this._vertexBuffers = {};
  76661. this._scene = scene;
  76662. }
  76663. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76664. if (this._colorShader) {
  76665. return;
  76666. }
  76667. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76668. attributes: [BABYLON.VertexBuffer.PositionKind],
  76669. uniforms: ["world", "viewProjection", "color"]
  76670. });
  76671. var engine = this._scene.getEngine();
  76672. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76673. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76674. this._createIndexBuffer();
  76675. };
  76676. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76677. var engine = this._scene.getEngine();
  76678. 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]);
  76679. };
  76680. BoundingBoxRenderer.prototype._rebuild = function () {
  76681. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76682. if (vb) {
  76683. vb._rebuild();
  76684. }
  76685. this._createIndexBuffer();
  76686. };
  76687. BoundingBoxRenderer.prototype.reset = function () {
  76688. this.renderList.reset();
  76689. };
  76690. BoundingBoxRenderer.prototype.render = function () {
  76691. if (this.renderList.length === 0) {
  76692. return;
  76693. }
  76694. this._prepareRessources();
  76695. if (!this._colorShader.isReady()) {
  76696. return;
  76697. }
  76698. var engine = this._scene.getEngine();
  76699. engine.setDepthWrite(false);
  76700. this._colorShader._preBind();
  76701. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76702. var boundingBox = this.renderList.data[boundingBoxIndex];
  76703. var min = boundingBox.minimum;
  76704. var max = boundingBox.maximum;
  76705. var diff = max.subtract(min);
  76706. var median = min.add(diff.scale(0.5));
  76707. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76708. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76709. .multiply(boundingBox.getWorldMatrix());
  76710. // VBOs
  76711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76712. if (this.showBackLines) {
  76713. // Back
  76714. engine.setDepthFunctionToGreaterOrEqual();
  76715. this._scene.resetCachedMaterial();
  76716. this._colorShader.setColor4("color", this.backColor.toColor4());
  76717. this._colorShader.bind(worldMatrix);
  76718. // Draw order
  76719. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76720. }
  76721. // Front
  76722. engine.setDepthFunctionToLess();
  76723. this._scene.resetCachedMaterial();
  76724. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76725. this._colorShader.bind(worldMatrix);
  76726. // Draw order
  76727. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76728. }
  76729. this._colorShader.unbind();
  76730. engine.setDepthFunctionToLessOrEqual();
  76731. engine.setDepthWrite(true);
  76732. };
  76733. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76734. this._prepareRessources();
  76735. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76736. return;
  76737. }
  76738. var engine = this._scene.getEngine();
  76739. engine.setDepthWrite(false);
  76740. engine.setColorWrite(false);
  76741. this._colorShader._preBind();
  76742. var boundingBox = mesh._boundingInfo.boundingBox;
  76743. var min = boundingBox.minimum;
  76744. var max = boundingBox.maximum;
  76745. var diff = max.subtract(min);
  76746. var median = min.add(diff.scale(0.5));
  76747. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76748. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76749. .multiply(boundingBox.getWorldMatrix());
  76750. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76751. engine.setDepthFunctionToLess();
  76752. this._scene.resetCachedMaterial();
  76753. this._colorShader.bind(worldMatrix);
  76754. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76755. this._colorShader.unbind();
  76756. engine.setDepthFunctionToLessOrEqual();
  76757. engine.setDepthWrite(true);
  76758. engine.setColorWrite(true);
  76759. };
  76760. BoundingBoxRenderer.prototype.dispose = function () {
  76761. if (!this._colorShader) {
  76762. return;
  76763. }
  76764. this.renderList.dispose();
  76765. this._colorShader.dispose();
  76766. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76767. if (buffer) {
  76768. buffer.dispose();
  76769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76770. }
  76771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76772. };
  76773. return BoundingBoxRenderer;
  76774. }());
  76775. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76776. })(BABYLON || (BABYLON = {}));
  76777. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76778. var BABYLON;
  76779. (function (BABYLON) {
  76780. var MorphTarget = /** @class */ (function () {
  76781. function MorphTarget(name, influence) {
  76782. if (influence === void 0) { influence = 0; }
  76783. this.name = name;
  76784. this.animations = new Array();
  76785. this._positions = null;
  76786. this._normals = null;
  76787. this._tangents = null;
  76788. this.onInfluenceChanged = new BABYLON.Observable();
  76789. this.influence = influence;
  76790. }
  76791. Object.defineProperty(MorphTarget.prototype, "influence", {
  76792. get: function () {
  76793. return this._influence;
  76794. },
  76795. set: function (influence) {
  76796. if (this._influence === influence) {
  76797. return;
  76798. }
  76799. var previous = this._influence;
  76800. this._influence = influence;
  76801. if (this.onInfluenceChanged.hasObservers) {
  76802. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76803. }
  76804. },
  76805. enumerable: true,
  76806. configurable: true
  76807. });
  76808. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76809. get: function () {
  76810. return !!this._positions;
  76811. },
  76812. enumerable: true,
  76813. configurable: true
  76814. });
  76815. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76816. get: function () {
  76817. return !!this._normals;
  76818. },
  76819. enumerable: true,
  76820. configurable: true
  76821. });
  76822. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76823. get: function () {
  76824. return !!this._tangents;
  76825. },
  76826. enumerable: true,
  76827. configurable: true
  76828. });
  76829. MorphTarget.prototype.setPositions = function (data) {
  76830. this._positions = data;
  76831. };
  76832. MorphTarget.prototype.getPositions = function () {
  76833. return this._positions;
  76834. };
  76835. MorphTarget.prototype.setNormals = function (data) {
  76836. this._normals = data;
  76837. };
  76838. MorphTarget.prototype.getNormals = function () {
  76839. return this._normals;
  76840. };
  76841. MorphTarget.prototype.setTangents = function (data) {
  76842. this._tangents = data;
  76843. };
  76844. MorphTarget.prototype.getTangents = function () {
  76845. return this._tangents;
  76846. };
  76847. /**
  76848. * Serializes the current target into a Serialization object.
  76849. * Returns the serialized object.
  76850. */
  76851. MorphTarget.prototype.serialize = function () {
  76852. var serializationObject = {};
  76853. serializationObject.name = this.name;
  76854. serializationObject.influence = this.influence;
  76855. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76856. if (this.hasNormals) {
  76857. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76858. }
  76859. if (this.hasTangents) {
  76860. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76861. }
  76862. // Animations
  76863. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76864. return serializationObject;
  76865. };
  76866. // Statics
  76867. MorphTarget.Parse = function (serializationObject) {
  76868. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76869. result.setPositions(serializationObject.positions);
  76870. if (serializationObject.normals) {
  76871. result.setNormals(serializationObject.normals);
  76872. }
  76873. if (serializationObject.tangents) {
  76874. result.setTangents(serializationObject.tangents);
  76875. }
  76876. // Animations
  76877. if (serializationObject.animations) {
  76878. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  76879. var parsedAnimation = serializationObject.animations[animationIndex];
  76880. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  76881. }
  76882. }
  76883. return result;
  76884. };
  76885. MorphTarget.FromMesh = function (mesh, name, influence) {
  76886. if (!name) {
  76887. name = mesh.name;
  76888. }
  76889. var result = new MorphTarget(name, influence);
  76890. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76891. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76892. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  76893. }
  76894. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  76895. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  76896. }
  76897. return result;
  76898. };
  76899. return MorphTarget;
  76900. }());
  76901. BABYLON.MorphTarget = MorphTarget;
  76902. })(BABYLON || (BABYLON = {}));
  76903. //# sourceMappingURL=babylon.morphTarget.js.map
  76904. var BABYLON;
  76905. (function (BABYLON) {
  76906. var MorphTargetManager = /** @class */ (function () {
  76907. function MorphTargetManager(scene) {
  76908. if (scene === void 0) { scene = null; }
  76909. this._targets = new Array();
  76910. this._targetObservable = new Array();
  76911. this._activeTargets = new BABYLON.SmartArray(16);
  76912. this._supportsNormals = false;
  76913. this._supportsTangents = false;
  76914. this._vertexCount = 0;
  76915. this._uniqueId = 0;
  76916. this._tempInfluences = new Array();
  76917. if (!scene) {
  76918. scene = BABYLON.Engine.LastCreatedScene;
  76919. }
  76920. this._scene = scene;
  76921. if (this._scene) {
  76922. this._scene.morphTargetManagers.push(this);
  76923. this._uniqueId = this._scene.getUniqueId();
  76924. }
  76925. }
  76926. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  76927. get: function () {
  76928. return this._uniqueId;
  76929. },
  76930. enumerable: true,
  76931. configurable: true
  76932. });
  76933. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  76934. get: function () {
  76935. return this._vertexCount;
  76936. },
  76937. enumerable: true,
  76938. configurable: true
  76939. });
  76940. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  76941. get: function () {
  76942. return this._supportsNormals;
  76943. },
  76944. enumerable: true,
  76945. configurable: true
  76946. });
  76947. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  76948. get: function () {
  76949. return this._supportsTangents;
  76950. },
  76951. enumerable: true,
  76952. configurable: true
  76953. });
  76954. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  76955. get: function () {
  76956. return this._targets.length;
  76957. },
  76958. enumerable: true,
  76959. configurable: true
  76960. });
  76961. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  76962. get: function () {
  76963. return this._activeTargets.length;
  76964. },
  76965. enumerable: true,
  76966. configurable: true
  76967. });
  76968. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  76969. get: function () {
  76970. return this._influences;
  76971. },
  76972. enumerable: true,
  76973. configurable: true
  76974. });
  76975. MorphTargetManager.prototype.getActiveTarget = function (index) {
  76976. return this._activeTargets.data[index];
  76977. };
  76978. MorphTargetManager.prototype.getTarget = function (index) {
  76979. return this._targets[index];
  76980. };
  76981. MorphTargetManager.prototype.addTarget = function (target) {
  76982. var _this = this;
  76983. this._targets.push(target);
  76984. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  76985. _this._syncActiveTargets(needUpdate);
  76986. }));
  76987. this._syncActiveTargets(true);
  76988. };
  76989. MorphTargetManager.prototype.removeTarget = function (target) {
  76990. var index = this._targets.indexOf(target);
  76991. if (index >= 0) {
  76992. this._targets.splice(index, 1);
  76993. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  76994. this._syncActiveTargets(true);
  76995. }
  76996. };
  76997. /**
  76998. * Serializes the current manager into a Serialization object.
  76999. * Returns the serialized object.
  77000. */
  77001. MorphTargetManager.prototype.serialize = function () {
  77002. var serializationObject = {};
  77003. serializationObject.id = this.uniqueId;
  77004. serializationObject.targets = [];
  77005. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77006. var target = _a[_i];
  77007. serializationObject.targets.push(target.serialize());
  77008. }
  77009. return serializationObject;
  77010. };
  77011. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77012. var influenceCount = 0;
  77013. this._activeTargets.reset();
  77014. this._supportsNormals = true;
  77015. this._supportsTangents = true;
  77016. this._vertexCount = 0;
  77017. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77018. var target = _a[_i];
  77019. this._activeTargets.push(target);
  77020. this._tempInfluences[influenceCount++] = target.influence;
  77021. var positions = target.getPositions();
  77022. if (positions) {
  77023. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77024. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77025. var vertexCount = positions.length / 3;
  77026. if (this._vertexCount === 0) {
  77027. this._vertexCount = vertexCount;
  77028. }
  77029. else if (this._vertexCount !== vertexCount) {
  77030. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77031. return;
  77032. }
  77033. }
  77034. }
  77035. if (!this._influences || this._influences.length !== influenceCount) {
  77036. this._influences = new Float32Array(influenceCount);
  77037. }
  77038. for (var index = 0; index < influenceCount; index++) {
  77039. this._influences[index] = this._tempInfluences[index];
  77040. }
  77041. if (needUpdate && this._scene) {
  77042. // Flag meshes as dirty to resync with the active targets
  77043. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77044. var mesh = _c[_b];
  77045. if (mesh.morphTargetManager === this) {
  77046. mesh._syncGeometryWithMorphTargetManager();
  77047. }
  77048. }
  77049. }
  77050. };
  77051. // Statics
  77052. MorphTargetManager.Parse = function (serializationObject, scene) {
  77053. var result = new MorphTargetManager(scene);
  77054. result._uniqueId = serializationObject.id;
  77055. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77056. var targetData = _a[_i];
  77057. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77058. }
  77059. return result;
  77060. };
  77061. return MorphTargetManager;
  77062. }());
  77063. BABYLON.MorphTargetManager = MorphTargetManager;
  77064. })(BABYLON || (BABYLON = {}));
  77065. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77066. var BABYLON;
  77067. (function (BABYLON) {
  77068. var Octree = /** @class */ (function () {
  77069. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77070. if (maxDepth === void 0) { maxDepth = 2; }
  77071. this.maxDepth = maxDepth;
  77072. this.dynamicContent = new Array();
  77073. this._maxBlockCapacity = maxBlockCapacity || 64;
  77074. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77075. this._creationFunc = creationFunc;
  77076. }
  77077. // Methods
  77078. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77079. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77080. };
  77081. Octree.prototype.addMesh = function (entry) {
  77082. for (var index = 0; index < this.blocks.length; index++) {
  77083. var block = this.blocks[index];
  77084. block.addEntry(entry);
  77085. }
  77086. };
  77087. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77088. this._selectionContent.reset();
  77089. for (var index = 0; index < this.blocks.length; index++) {
  77090. var block = this.blocks[index];
  77091. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77092. }
  77093. if (allowDuplicate) {
  77094. this._selectionContent.concat(this.dynamicContent);
  77095. }
  77096. else {
  77097. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77098. }
  77099. return this._selectionContent;
  77100. };
  77101. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77102. this._selectionContent.reset();
  77103. for (var index = 0; index < this.blocks.length; index++) {
  77104. var block = this.blocks[index];
  77105. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77106. }
  77107. if (allowDuplicate) {
  77108. this._selectionContent.concat(this.dynamicContent);
  77109. }
  77110. else {
  77111. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77112. }
  77113. return this._selectionContent;
  77114. };
  77115. Octree.prototype.intersectsRay = function (ray) {
  77116. this._selectionContent.reset();
  77117. for (var index = 0; index < this.blocks.length; index++) {
  77118. var block = this.blocks[index];
  77119. block.intersectsRay(ray, this._selectionContent);
  77120. }
  77121. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77122. return this._selectionContent;
  77123. };
  77124. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77125. target.blocks = new Array();
  77126. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77127. // Segmenting space
  77128. for (var x = 0; x < 2; x++) {
  77129. for (var y = 0; y < 2; y++) {
  77130. for (var z = 0; z < 2; z++) {
  77131. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77132. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77133. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77134. block.addEntries(entries);
  77135. target.blocks.push(block);
  77136. }
  77137. }
  77138. }
  77139. };
  77140. Octree.CreationFuncForMeshes = function (entry, block) {
  77141. var boundingInfo = entry.getBoundingInfo();
  77142. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77143. block.entries.push(entry);
  77144. }
  77145. };
  77146. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77147. var boundingInfo = entry.getBoundingInfo();
  77148. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77149. block.entries.push(entry);
  77150. }
  77151. };
  77152. return Octree;
  77153. }());
  77154. BABYLON.Octree = Octree;
  77155. })(BABYLON || (BABYLON = {}));
  77156. //# sourceMappingURL=babylon.octree.js.map
  77157. var BABYLON;
  77158. (function (BABYLON) {
  77159. var OctreeBlock = /** @class */ (function () {
  77160. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77161. this.entries = new Array();
  77162. this._boundingVectors = new Array();
  77163. this._capacity = capacity;
  77164. this._depth = depth;
  77165. this._maxDepth = maxDepth;
  77166. this._creationFunc = creationFunc;
  77167. this._minPoint = minPoint;
  77168. this._maxPoint = maxPoint;
  77169. this._boundingVectors.push(minPoint.clone());
  77170. this._boundingVectors.push(maxPoint.clone());
  77171. this._boundingVectors.push(minPoint.clone());
  77172. this._boundingVectors[2].x = maxPoint.x;
  77173. this._boundingVectors.push(minPoint.clone());
  77174. this._boundingVectors[3].y = maxPoint.y;
  77175. this._boundingVectors.push(minPoint.clone());
  77176. this._boundingVectors[4].z = maxPoint.z;
  77177. this._boundingVectors.push(maxPoint.clone());
  77178. this._boundingVectors[5].z = minPoint.z;
  77179. this._boundingVectors.push(maxPoint.clone());
  77180. this._boundingVectors[6].x = minPoint.x;
  77181. this._boundingVectors.push(maxPoint.clone());
  77182. this._boundingVectors[7].y = minPoint.y;
  77183. }
  77184. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77185. // Property
  77186. get: function () {
  77187. return this._capacity;
  77188. },
  77189. enumerable: true,
  77190. configurable: true
  77191. });
  77192. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77193. get: function () {
  77194. return this._minPoint;
  77195. },
  77196. enumerable: true,
  77197. configurable: true
  77198. });
  77199. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77200. get: function () {
  77201. return this._maxPoint;
  77202. },
  77203. enumerable: true,
  77204. configurable: true
  77205. });
  77206. // Methods
  77207. OctreeBlock.prototype.addEntry = function (entry) {
  77208. if (this.blocks) {
  77209. for (var index = 0; index < this.blocks.length; index++) {
  77210. var block = this.blocks[index];
  77211. block.addEntry(entry);
  77212. }
  77213. return;
  77214. }
  77215. this._creationFunc(entry, this);
  77216. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77217. this.createInnerBlocks();
  77218. }
  77219. };
  77220. OctreeBlock.prototype.addEntries = function (entries) {
  77221. for (var index = 0; index < entries.length; index++) {
  77222. var mesh = entries[index];
  77223. this.addEntry(mesh);
  77224. }
  77225. };
  77226. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77227. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77228. if (this.blocks) {
  77229. for (var index = 0; index < this.blocks.length; index++) {
  77230. var block = this.blocks[index];
  77231. block.select(frustumPlanes, selection, allowDuplicate);
  77232. }
  77233. return;
  77234. }
  77235. if (allowDuplicate) {
  77236. selection.concat(this.entries);
  77237. }
  77238. else {
  77239. selection.concatWithNoDuplicate(this.entries);
  77240. }
  77241. }
  77242. };
  77243. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77244. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77245. if (this.blocks) {
  77246. for (var index = 0; index < this.blocks.length; index++) {
  77247. var block = this.blocks[index];
  77248. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77249. }
  77250. return;
  77251. }
  77252. if (allowDuplicate) {
  77253. selection.concat(this.entries);
  77254. }
  77255. else {
  77256. selection.concatWithNoDuplicate(this.entries);
  77257. }
  77258. }
  77259. };
  77260. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77261. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77262. if (this.blocks) {
  77263. for (var index = 0; index < this.blocks.length; index++) {
  77264. var block = this.blocks[index];
  77265. block.intersectsRay(ray, selection);
  77266. }
  77267. return;
  77268. }
  77269. selection.concatWithNoDuplicate(this.entries);
  77270. }
  77271. };
  77272. OctreeBlock.prototype.createInnerBlocks = function () {
  77273. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77274. };
  77275. return OctreeBlock;
  77276. }());
  77277. BABYLON.OctreeBlock = OctreeBlock;
  77278. })(BABYLON || (BABYLON = {}));
  77279. //# sourceMappingURL=babylon.octreeBlock.js.map
  77280. var BABYLON;
  77281. (function (BABYLON) {
  77282. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77283. __extends(VRDistortionCorrectionPostProcess, _super);
  77284. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77285. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77286. 'LensCenter',
  77287. 'Scale',
  77288. 'ScaleIn',
  77289. 'HmdWarpParam'
  77290. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77291. _this._isRightEye = isRightEye;
  77292. _this._distortionFactors = vrMetrics.distortionK;
  77293. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77294. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77295. _this.adaptScaleToCurrentViewport = true;
  77296. _this.onSizeChangedObservable.add(function () {
  77297. _this.aspectRatio = _this.width * .5 / _this.height;
  77298. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77299. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77300. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77301. });
  77302. _this.onApplyObservable.add(function (effect) {
  77303. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77304. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77305. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77306. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77307. });
  77308. return _this;
  77309. }
  77310. return VRDistortionCorrectionPostProcess;
  77311. }(BABYLON.PostProcess));
  77312. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77313. })(BABYLON || (BABYLON = {}));
  77314. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77315. var BABYLON;
  77316. (function (BABYLON) {
  77317. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77318. __extends(AnaglyphPostProcess, _super);
  77319. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77320. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77321. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77322. _this.onApplyObservable.add(function (effect) {
  77323. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77324. });
  77325. return _this;
  77326. }
  77327. return AnaglyphPostProcess;
  77328. }(BABYLON.PostProcess));
  77329. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77330. })(BABYLON || (BABYLON = {}));
  77331. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77332. var BABYLON;
  77333. (function (BABYLON) {
  77334. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77335. __extends(StereoscopicInterlacePostProcess, _super);
  77336. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77337. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77338. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77339. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77340. _this.onSizeChangedObservable.add(function () {
  77341. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77342. });
  77343. _this.onApplyObservable.add(function (effect) {
  77344. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77345. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77346. });
  77347. return _this;
  77348. }
  77349. return StereoscopicInterlacePostProcess;
  77350. }(BABYLON.PostProcess));
  77351. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77352. })(BABYLON || (BABYLON = {}));
  77353. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77354. var BABYLON;
  77355. (function (BABYLON) {
  77356. /**
  77357. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77358. * Screen rotation is taken into account.
  77359. */
  77360. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77361. function FreeCameraDeviceOrientationInput() {
  77362. var _this = this;
  77363. this._screenOrientationAngle = 0;
  77364. this._screenQuaternion = new BABYLON.Quaternion();
  77365. this._alpha = 0;
  77366. this._beta = 0;
  77367. this._gamma = 0;
  77368. this._orientationChanged = function () {
  77369. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77370. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77371. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77372. };
  77373. this._deviceOrientation = function (evt) {
  77374. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77375. _this._beta = evt.beta !== null ? evt.beta : 0;
  77376. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77377. };
  77378. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77379. this._orientationChanged();
  77380. }
  77381. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77382. get: function () {
  77383. return this._camera;
  77384. },
  77385. set: function (camera) {
  77386. this._camera = camera;
  77387. if (this._camera != null && !this._camera.rotationQuaternion) {
  77388. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77389. }
  77390. },
  77391. enumerable: true,
  77392. configurable: true
  77393. });
  77394. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77395. window.addEventListener("orientationchange", this._orientationChanged);
  77396. window.addEventListener("deviceorientation", this._deviceOrientation);
  77397. //In certain cases, the attach control is called AFTER orientation was changed,
  77398. //So this is needed.
  77399. this._orientationChanged();
  77400. };
  77401. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77402. window.removeEventListener("orientationchange", this._orientationChanged);
  77403. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77404. };
  77405. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77406. //if no device orientation provided, don't update the rotation.
  77407. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77408. if (!this._alpha)
  77409. return;
  77410. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77411. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77412. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77413. //Mirror on XY Plane
  77414. this._camera.rotationQuaternion.z *= -1;
  77415. this._camera.rotationQuaternion.w *= -1;
  77416. };
  77417. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77418. return "FreeCameraDeviceOrientationInput";
  77419. };
  77420. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77421. return "deviceOrientation";
  77422. };
  77423. return FreeCameraDeviceOrientationInput;
  77424. }());
  77425. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77426. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77427. })(BABYLON || (BABYLON = {}));
  77428. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77429. var BABYLON;
  77430. (function (BABYLON) {
  77431. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77432. function ArcRotateCameraVRDeviceOrientationInput() {
  77433. this.alphaCorrection = 1;
  77434. this.betaCorrection = 1;
  77435. this.gammaCorrection = 1;
  77436. this._alpha = 0;
  77437. this._gamma = 0;
  77438. this._dirty = false;
  77439. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77440. }
  77441. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77442. this.camera.attachControl(element, noPreventDefault);
  77443. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77444. };
  77445. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77446. if (evt.alpha !== null) {
  77447. this._alpha = +evt.alpha | 0;
  77448. }
  77449. if (evt.gamma !== null) {
  77450. this._gamma = +evt.gamma | 0;
  77451. }
  77452. this._dirty = true;
  77453. };
  77454. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77455. if (this._dirty) {
  77456. this._dirty = false;
  77457. if (this._gamma < 0) {
  77458. this._gamma = 180 + this._gamma;
  77459. }
  77460. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77461. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77462. }
  77463. };
  77464. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77465. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77466. };
  77467. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77468. return "ArcRotateCameraVRDeviceOrientationInput";
  77469. };
  77470. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77471. return "VRDeviceOrientation";
  77472. };
  77473. return ArcRotateCameraVRDeviceOrientationInput;
  77474. }());
  77475. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77476. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77477. })(BABYLON || (BABYLON = {}));
  77478. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77479. var BABYLON;
  77480. (function (BABYLON) {
  77481. var VRCameraMetrics = /** @class */ (function () {
  77482. function VRCameraMetrics() {
  77483. this.compensateDistortion = true;
  77484. }
  77485. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77486. get: function () {
  77487. return this.hResolution / (2 * this.vResolution);
  77488. },
  77489. enumerable: true,
  77490. configurable: true
  77491. });
  77492. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77493. get: function () {
  77494. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77495. },
  77496. enumerable: true,
  77497. configurable: true
  77498. });
  77499. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77500. get: function () {
  77501. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77502. var h = (4 * meters) / this.hScreenSize;
  77503. return BABYLON.Matrix.Translation(h, 0, 0);
  77504. },
  77505. enumerable: true,
  77506. configurable: true
  77507. });
  77508. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77509. get: function () {
  77510. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77511. var h = (4 * meters) / this.hScreenSize;
  77512. return BABYLON.Matrix.Translation(-h, 0, 0);
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77518. get: function () {
  77519. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77520. },
  77521. enumerable: true,
  77522. configurable: true
  77523. });
  77524. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77525. get: function () {
  77526. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77527. },
  77528. enumerable: true,
  77529. configurable: true
  77530. });
  77531. VRCameraMetrics.GetDefault = function () {
  77532. var result = new VRCameraMetrics();
  77533. result.hResolution = 1280;
  77534. result.vResolution = 800;
  77535. result.hScreenSize = 0.149759993;
  77536. result.vScreenSize = 0.0935999975;
  77537. result.vScreenCenter = 0.0467999987;
  77538. result.eyeToScreenDistance = 0.0410000011;
  77539. result.lensSeparationDistance = 0.0635000020;
  77540. result.interpupillaryDistance = 0.0640000030;
  77541. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77542. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77543. result.postProcessScaleFactor = 1.714605507808412;
  77544. result.lensCenterOffset = 0.151976421;
  77545. return result;
  77546. };
  77547. return VRCameraMetrics;
  77548. }());
  77549. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77550. })(BABYLON || (BABYLON = {}));
  77551. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77552. var BABYLON;
  77553. (function (BABYLON) {
  77554. /**
  77555. * This represents a WebVR camera.
  77556. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77557. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77558. */
  77559. var WebVRFreeCamera = /** @class */ (function (_super) {
  77560. __extends(WebVRFreeCamera, _super);
  77561. /**
  77562. * Instantiates a WebVRFreeCamera.
  77563. * @param name The name of the WebVRFreeCamera
  77564. * @param position The starting anchor position for the camera
  77565. * @param scene The scene the camera belongs to
  77566. * @param webVROptions a set of customizable options for the webVRCamera
  77567. */
  77568. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77569. if (webVROptions === void 0) { webVROptions = {}; }
  77570. var _this = _super.call(this, name, position, scene) || this;
  77571. _this.webVROptions = webVROptions;
  77572. /**
  77573. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77574. */
  77575. _this._vrDevice = null;
  77576. /**
  77577. * The rawPose of the vrDevice.
  77578. */
  77579. _this.rawPose = null;
  77580. _this._specsVersion = "1.1";
  77581. _this._attached = false;
  77582. _this._descendants = [];
  77583. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77584. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77585. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77586. _this._standingMatrix = null;
  77587. /**
  77588. * Represents device position in babylon space.
  77589. */
  77590. _this.devicePosition = BABYLON.Vector3.Zero();
  77591. /**
  77592. * Represents device rotation in babylon space.
  77593. */
  77594. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77595. /**
  77596. * The scale of the device to be used when translating from device space to babylon space.
  77597. */
  77598. _this.deviceScaleFactor = 1;
  77599. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77600. _this._worldToDevice = BABYLON.Matrix.Identity();
  77601. /**
  77602. * References to the webVR controllers for the vrDevice.
  77603. */
  77604. _this.controllers = [];
  77605. /**
  77606. * Emits an event when a controller is attached.
  77607. */
  77608. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77609. /**
  77610. * Emits an event when a controller's mesh has been loaded;
  77611. */
  77612. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77613. /**
  77614. * If the rig cameras be used as parent instead of this camera.
  77615. */
  77616. _this.rigParenting = true;
  77617. _this._defaultHeight = undefined;
  77618. _this._workingVector = BABYLON.Vector3.Zero();
  77619. _this._oneVector = BABYLON.Vector3.One();
  77620. _this._workingMatrix = BABYLON.Matrix.Identity();
  77621. _this._cache.position = BABYLON.Vector3.Zero();
  77622. if (webVROptions.defaultHeight) {
  77623. _this._defaultHeight = webVROptions.defaultHeight;
  77624. _this.position.y = _this._defaultHeight;
  77625. }
  77626. _this.minZ = 0.1;
  77627. //legacy support - the compensation boolean was removed.
  77628. if (arguments.length === 5) {
  77629. _this.webVROptions = arguments[4];
  77630. }
  77631. // default webVR options
  77632. if (_this.webVROptions.trackPosition == undefined) {
  77633. _this.webVROptions.trackPosition = true;
  77634. }
  77635. if (_this.webVROptions.controllerMeshes == undefined) {
  77636. _this.webVROptions.controllerMeshes = true;
  77637. }
  77638. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77639. _this.webVROptions.defaultLightingOnControllers = true;
  77640. }
  77641. _this.rotationQuaternion = new BABYLON.Quaternion();
  77642. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77643. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77644. }
  77645. //enable VR
  77646. var engine = _this.getEngine();
  77647. _this._onVREnabled = function (success) { if (success) {
  77648. _this.initControllers();
  77649. } };
  77650. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77651. engine.initWebVR().add(function (event) {
  77652. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77653. return;
  77654. }
  77655. _this._vrDevice = event.vrDisplay;
  77656. //reset the rig parameters.
  77657. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77658. if (_this._attached) {
  77659. _this.getEngine().enableVR();
  77660. }
  77661. });
  77662. if (typeof (VRFrameData) !== "undefined")
  77663. _this._frameData = new VRFrameData();
  77664. /**
  77665. * The idea behind the following lines:
  77666. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77667. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77668. * the second will not show it correctly.
  77669. *
  77670. * To solve this - each object that has the camera as parent will be added to a protected array.
  77671. * When the rig camera renders, it will take this array and set all of those to be its children.
  77672. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77673. * Amazing!
  77674. */
  77675. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77676. if (camera.parent === _this && _this.rigParenting) {
  77677. _this._descendants = _this.getDescendants(true, function (n) {
  77678. // don't take the cameras or the controllers!
  77679. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77680. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77681. return !isController && !isRigCamera;
  77682. });
  77683. _this._descendants.forEach(function (node) {
  77684. node.parent = camera;
  77685. });
  77686. }
  77687. });
  77688. scene.onAfterCameraRenderObservable.add(function (camera) {
  77689. if (camera.parent === _this && _this.rigParenting) {
  77690. _this._descendants.forEach(function (node) {
  77691. node.parent = _this;
  77692. });
  77693. }
  77694. });
  77695. return _this;
  77696. }
  77697. /**
  77698. * Gets the device distance from the ground.
  77699. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77700. */
  77701. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77702. if (this._standingMatrix && this._defaultHeight === undefined) {
  77703. // Add standing matrix offset to get real offset from ground in room
  77704. this._standingMatrix.getTranslationToRef(this._workingVector);
  77705. return this._deviceRoomPosition.y + this._workingVector.y;
  77706. }
  77707. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77708. return this._defaultHeight || 0;
  77709. };
  77710. /**
  77711. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77712. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77713. */
  77714. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77715. var _this = this;
  77716. if (callback === void 0) { callback = function (bool) { }; }
  77717. // Use standing matrix if available
  77718. if (!navigator || !navigator.getVRDisplays) {
  77719. callback(false);
  77720. }
  77721. else {
  77722. navigator.getVRDisplays().then(function (displays) {
  77723. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77724. callback(false);
  77725. }
  77726. else {
  77727. _this._standingMatrix = new BABYLON.Matrix();
  77728. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77729. if (!_this.getScene().useRightHandedSystem) {
  77730. [2, 6, 8, 9, 14].forEach(function (num) {
  77731. if (_this._standingMatrix) {
  77732. _this._standingMatrix.m[num] *= -1;
  77733. }
  77734. });
  77735. }
  77736. callback(true);
  77737. }
  77738. });
  77739. }
  77740. };
  77741. /**
  77742. * Disposes the camera
  77743. */
  77744. WebVRFreeCamera.prototype.dispose = function () {
  77745. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77746. _super.prototype.dispose.call(this);
  77747. };
  77748. /**
  77749. * Gets a vrController by name.
  77750. * @param name The name of the controller to retreive
  77751. * @returns the controller matching the name specified or null if not found
  77752. */
  77753. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77754. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77755. var gp = _a[_i];
  77756. if (gp.hand === name) {
  77757. return gp;
  77758. }
  77759. }
  77760. return null;
  77761. };
  77762. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77763. /**
  77764. * The controller corrisponding to the users left hand.
  77765. */
  77766. get: function () {
  77767. if (!this._leftController) {
  77768. this._leftController = this.getControllerByName("left");
  77769. }
  77770. return this._leftController;
  77771. },
  77772. enumerable: true,
  77773. configurable: true
  77774. });
  77775. ;
  77776. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77777. /**
  77778. * The controller corrisponding to the users right hand.
  77779. */
  77780. get: function () {
  77781. if (!this._rightController) {
  77782. this._rightController = this.getControllerByName("right");
  77783. }
  77784. return this._rightController;
  77785. },
  77786. enumerable: true,
  77787. configurable: true
  77788. });
  77789. ;
  77790. /**
  77791. * Casts a ray forward from the vrCamera's gaze.
  77792. * @param length Length of the ray (default: 100)
  77793. * @returns the ray corrisponding to the gaze
  77794. */
  77795. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77796. if (length === void 0) { length = 100; }
  77797. if (this.leftCamera) {
  77798. // Use left eye to avoid computation to compute center on every call
  77799. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77800. }
  77801. else {
  77802. return _super.prototype.getForwardRay.call(this, length);
  77803. }
  77804. };
  77805. /**
  77806. * Updates the camera based on device's frame data
  77807. */
  77808. WebVRFreeCamera.prototype._checkInputs = function () {
  77809. if (this._vrDevice && this._vrDevice.isPresenting) {
  77810. this._vrDevice.getFrameData(this._frameData);
  77811. this.updateFromDevice(this._frameData.pose);
  77812. }
  77813. _super.prototype._checkInputs.call(this);
  77814. };
  77815. /**
  77816. * Updates the poseControlled values based on the input device pose.
  77817. * @param poseData Pose coming from the device
  77818. */
  77819. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77820. if (poseData && poseData.orientation) {
  77821. this.rawPose = poseData;
  77822. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77823. if (this.getScene().useRightHandedSystem) {
  77824. this._deviceRoomRotationQuaternion.z *= -1;
  77825. this._deviceRoomRotationQuaternion.w *= -1;
  77826. }
  77827. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77828. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77829. if (this.getScene().useRightHandedSystem) {
  77830. this._deviceRoomPosition.z *= -1;
  77831. }
  77832. }
  77833. }
  77834. };
  77835. /**
  77836. * WebVR's attach control will start broadcasting frames to the device.
  77837. * Note that in certain browsers (chrome for example) this function must be called
  77838. * within a user-interaction callback. Example:
  77839. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77840. *
  77841. * @param element html element to attach the vrDevice to
  77842. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77843. */
  77844. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77845. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77846. this._attached = true;
  77847. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77848. if (this._vrDevice) {
  77849. this.getEngine().enableVR();
  77850. }
  77851. };
  77852. /**
  77853. * Detaches the camera from the html element and disables VR
  77854. *
  77855. * @param element html element to detach from
  77856. */
  77857. WebVRFreeCamera.prototype.detachControl = function (element) {
  77858. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77859. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77860. _super.prototype.detachControl.call(this, element);
  77861. this._attached = false;
  77862. this.getEngine().disableVR();
  77863. };
  77864. /**
  77865. * @returns the name of this class
  77866. */
  77867. WebVRFreeCamera.prototype.getClassName = function () {
  77868. return "WebVRFreeCamera";
  77869. };
  77870. /**
  77871. * Calls resetPose on the vrDisplay
  77872. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77873. */
  77874. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77875. //uses the vrDisplay's "resetPose()".
  77876. //pitch and roll won't be affected.
  77877. this._vrDevice.resetPose();
  77878. };
  77879. /**
  77880. * Updates the rig cameras (left and right eye)
  77881. */
  77882. WebVRFreeCamera.prototype._updateRigCameras = function () {
  77883. var camLeft = this._rigCameras[0];
  77884. var camRight = this._rigCameras[1];
  77885. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77886. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77887. camLeft.position.copyFrom(this._deviceRoomPosition);
  77888. camRight.position.copyFrom(this._deviceRoomPosition);
  77889. };
  77890. /**
  77891. * Updates the cached values of the camera
  77892. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  77893. */
  77894. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  77895. var _this = this;
  77896. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  77897. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  77898. if (!this.updateCacheCalled) {
  77899. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  77900. this.updateCacheCalled = true;
  77901. this.update();
  77902. }
  77903. // Set working vector to the device position in room space rotated by the new rotation
  77904. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  77905. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  77906. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  77907. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  77908. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  77909. // Add translation from anchor position
  77910. this._deviceToWorld.getTranslationToRef(this._workingVector);
  77911. this._workingVector.addInPlace(this.position);
  77912. this._workingVector.subtractInPlace(this._cache.position);
  77913. this._deviceToWorld.setTranslation(this._workingVector);
  77914. // Set an inverted matrix to be used when updating the camera
  77915. this._deviceToWorld.invertToRef(this._worldToDevice);
  77916. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  77917. this.controllers.forEach(function (controller) {
  77918. controller._deviceToWorld = _this._deviceToWorld;
  77919. controller.update();
  77920. });
  77921. }
  77922. if (!ignoreParentClass) {
  77923. _super.prototype._updateCache.call(this);
  77924. }
  77925. this.updateCacheCalled = false;
  77926. };
  77927. /**
  77928. * Updates the current device position and rotation in the babylon world
  77929. */
  77930. WebVRFreeCamera.prototype.update = function () {
  77931. // Get current device position in babylon world
  77932. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  77933. // Get current device rotation in babylon world
  77934. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  77935. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  77936. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77937. _super.prototype.update.call(this);
  77938. };
  77939. /**
  77940. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  77941. * @returns an identity matrix
  77942. */
  77943. WebVRFreeCamera.prototype._getViewMatrix = function () {
  77944. return BABYLON.Matrix.Identity();
  77945. };
  77946. /**
  77947. * This function is called by the two RIG cameras.
  77948. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  77949. */
  77950. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  77951. var _this = this;
  77952. //WebVR 1.1
  77953. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  77954. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  77955. if (!this.getScene().useRightHandedSystem) {
  77956. [2, 6, 8, 9, 14].forEach(function (num) {
  77957. _this._webvrViewMatrix.m[num] *= -1;
  77958. });
  77959. }
  77960. // update the camera rotation matrix
  77961. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  77962. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  77963. // Computing target and final matrix
  77964. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  77965. var parentCamera = this._cameraRigParams["parentCamera"];
  77966. // should the view matrix be updated with scale and position offset?
  77967. if (parentCamera.deviceScaleFactor !== 1) {
  77968. this._webvrViewMatrix.invert();
  77969. // scale the position, if set
  77970. if (parentCamera.deviceScaleFactor) {
  77971. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  77972. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  77973. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  77974. }
  77975. this._webvrViewMatrix.invert();
  77976. }
  77977. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  77978. return this._webvrViewMatrix;
  77979. };
  77980. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  77981. var _this = this;
  77982. var parentCamera = this.parent;
  77983. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  77984. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  77985. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  77986. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  77987. //babylon compatible matrix
  77988. if (!this.getScene().useRightHandedSystem) {
  77989. [8, 9, 10, 11].forEach(function (num) {
  77990. _this._projectionMatrix.m[num] *= -1;
  77991. });
  77992. }
  77993. return this._projectionMatrix;
  77994. };
  77995. /**
  77996. * Initializes the controllers and their meshes
  77997. */
  77998. WebVRFreeCamera.prototype.initControllers = function () {
  77999. var _this = this;
  78000. this.controllers = [];
  78001. var manager = this.getScene().gamepadManager;
  78002. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78003. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78004. var webVrController = gamepad;
  78005. if (webVrController.defaultModel) {
  78006. webVrController.defaultModel.setEnabled(false);
  78007. }
  78008. if (webVrController.hand === "right") {
  78009. _this._rightController = null;
  78010. }
  78011. if (webVrController.hand === "left") {
  78012. _this._rightController = null;
  78013. }
  78014. var controllerIndex = _this.controllers.indexOf(webVrController);
  78015. if (controllerIndex !== -1) {
  78016. _this.controllers.splice(controllerIndex, 1);
  78017. }
  78018. }
  78019. });
  78020. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78021. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78022. var webVrController_1 = gamepad;
  78023. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78024. if (_this.webVROptions.controllerMeshes) {
  78025. if (webVrController_1.defaultModel) {
  78026. webVrController_1.defaultModel.setEnabled(true);
  78027. }
  78028. else {
  78029. // Load the meshes
  78030. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78031. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78032. if (_this.webVROptions.defaultLightingOnControllers) {
  78033. if (!_this._lightOnControllers) {
  78034. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78035. }
  78036. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78037. var children = mesh.getChildren();
  78038. if (children.length !== 0) {
  78039. children.forEach(function (mesh) {
  78040. light.includedOnlyMeshes.push(mesh);
  78041. activateLightOnSubMeshes_1(mesh, light);
  78042. });
  78043. }
  78044. };
  78045. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78046. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78047. }
  78048. });
  78049. }
  78050. }
  78051. webVrController_1.attachToPoseControlledCamera(_this);
  78052. // since this is async - sanity check. Is the controller already stored?
  78053. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78054. //add to the controllers array
  78055. _this.controllers.push(webVrController_1);
  78056. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78057. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78058. // So we're overriding setting left & right manually to be sure
  78059. var firstViveWandDetected = false;
  78060. for (var i = 0; i < _this.controllers.length; i++) {
  78061. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78062. if (!firstViveWandDetected) {
  78063. firstViveWandDetected = true;
  78064. _this.controllers[i].hand = "left";
  78065. }
  78066. else {
  78067. _this.controllers[i].hand = "right";
  78068. }
  78069. }
  78070. }
  78071. //did we find enough controllers? Great! let the developer know.
  78072. if (_this.controllers.length >= 2) {
  78073. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78074. }
  78075. }
  78076. }
  78077. });
  78078. };
  78079. return WebVRFreeCamera;
  78080. }(BABYLON.FreeCamera));
  78081. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78082. })(BABYLON || (BABYLON = {}));
  78083. //# sourceMappingURL=babylon.webVRCamera.js.map
  78084. var BABYLON;
  78085. (function (BABYLON) {
  78086. // We're mainly based on the logic defined into the FreeCamera code
  78087. /**
  78088. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78089. * being tilted forward or back and left or right.
  78090. */
  78091. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78092. __extends(DeviceOrientationCamera, _super);
  78093. /**
  78094. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78095. * @param name The name of the camera
  78096. * @param position The start position camera
  78097. * @param scene The scene the camera belongs to
  78098. */
  78099. function DeviceOrientationCamera(name, position, scene) {
  78100. var _this = _super.call(this, name, position, scene) || this;
  78101. _this._quaternionCache = new BABYLON.Quaternion();
  78102. _this.inputs.addDeviceOrientation();
  78103. return _this;
  78104. }
  78105. /**
  78106. * Gets the current instance class name ("DeviceOrientationCamera").
  78107. * This helps avoiding instanceof at run time.
  78108. * @returns the class name
  78109. */
  78110. DeviceOrientationCamera.prototype.getClassName = function () {
  78111. return "DeviceOrientationCamera";
  78112. };
  78113. /**
  78114. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78115. */
  78116. DeviceOrientationCamera.prototype._checkInputs = function () {
  78117. _super.prototype._checkInputs.call(this);
  78118. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78119. if (this._initialQuaternion) {
  78120. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78121. }
  78122. };
  78123. /**
  78124. * Reset the camera to its default orientation on the specified axis only.
  78125. * @param axis The axis to reset
  78126. */
  78127. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78128. var _this = this;
  78129. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78130. //can only work if this camera has a rotation quaternion already.
  78131. if (!this.rotationQuaternion)
  78132. return;
  78133. if (!this._initialQuaternion) {
  78134. this._initialQuaternion = new BABYLON.Quaternion();
  78135. }
  78136. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78137. ['x', 'y', 'z'].forEach(function (axisName) {
  78138. if (!axis[axisName]) {
  78139. _this._initialQuaternion[axisName] = 0;
  78140. }
  78141. else {
  78142. _this._initialQuaternion[axisName] *= -1;
  78143. }
  78144. });
  78145. this._initialQuaternion.normalize();
  78146. //force rotation update
  78147. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78148. };
  78149. return DeviceOrientationCamera;
  78150. }(BABYLON.FreeCamera));
  78151. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78152. })(BABYLON || (BABYLON = {}));
  78153. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78154. var BABYLON;
  78155. (function (BABYLON) {
  78156. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78157. __extends(VRDeviceOrientationFreeCamera, _super);
  78158. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78159. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78160. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78161. var _this = _super.call(this, name, position, scene) || this;
  78162. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78163. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78164. return _this;
  78165. }
  78166. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78167. return "VRDeviceOrientationFreeCamera";
  78168. };
  78169. return VRDeviceOrientationFreeCamera;
  78170. }(BABYLON.DeviceOrientationCamera));
  78171. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78172. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78173. __extends(VRDeviceOrientationGamepadCamera, _super);
  78174. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78175. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78176. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78177. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78178. _this.inputs.addGamepad();
  78179. return _this;
  78180. }
  78181. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78182. return "VRDeviceOrientationGamepadCamera";
  78183. };
  78184. return VRDeviceOrientationGamepadCamera;
  78185. }(VRDeviceOrientationFreeCamera));
  78186. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78187. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78188. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78189. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78190. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78191. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78192. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78193. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78194. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78195. _this.inputs.addVRDeviceOrientation();
  78196. return _this;
  78197. }
  78198. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78199. return "VRDeviceOrientationArcRotateCamera";
  78200. };
  78201. return VRDeviceOrientationArcRotateCamera;
  78202. }(BABYLON.ArcRotateCamera));
  78203. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78204. })(BABYLON || (BABYLON = {}));
  78205. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78206. var BABYLON;
  78207. (function (BABYLON) {
  78208. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78209. __extends(AnaglyphFreeCamera, _super);
  78210. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78211. var _this = _super.call(this, name, position, scene) || this;
  78212. _this.interaxialDistance = interaxialDistance;
  78213. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78214. return _this;
  78215. }
  78216. AnaglyphFreeCamera.prototype.getClassName = function () {
  78217. return "AnaglyphFreeCamera";
  78218. };
  78219. return AnaglyphFreeCamera;
  78220. }(BABYLON.FreeCamera));
  78221. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78222. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78223. __extends(AnaglyphArcRotateCamera, _super);
  78224. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78225. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78226. _this.interaxialDistance = interaxialDistance;
  78227. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78228. return _this;
  78229. }
  78230. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78231. return "AnaglyphArcRotateCamera";
  78232. };
  78233. return AnaglyphArcRotateCamera;
  78234. }(BABYLON.ArcRotateCamera));
  78235. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78236. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78237. __extends(AnaglyphGamepadCamera, _super);
  78238. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78239. var _this = _super.call(this, name, position, scene) || this;
  78240. _this.interaxialDistance = interaxialDistance;
  78241. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78242. return _this;
  78243. }
  78244. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78245. return "AnaglyphGamepadCamera";
  78246. };
  78247. return AnaglyphGamepadCamera;
  78248. }(BABYLON.GamepadCamera));
  78249. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78250. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78251. __extends(AnaglyphUniversalCamera, _super);
  78252. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78253. var _this = _super.call(this, name, position, scene) || this;
  78254. _this.interaxialDistance = interaxialDistance;
  78255. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78256. return _this;
  78257. }
  78258. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78259. return "AnaglyphUniversalCamera";
  78260. };
  78261. return AnaglyphUniversalCamera;
  78262. }(BABYLON.UniversalCamera));
  78263. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78264. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78265. __extends(StereoscopicFreeCamera, _super);
  78266. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78267. var _this = _super.call(this, name, position, scene) || this;
  78268. _this.interaxialDistance = interaxialDistance;
  78269. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78270. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78271. return _this;
  78272. }
  78273. StereoscopicFreeCamera.prototype.getClassName = function () {
  78274. return "StereoscopicFreeCamera";
  78275. };
  78276. return StereoscopicFreeCamera;
  78277. }(BABYLON.FreeCamera));
  78278. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78279. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78280. __extends(StereoscopicArcRotateCamera, _super);
  78281. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78282. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78283. _this.interaxialDistance = interaxialDistance;
  78284. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78285. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78286. return _this;
  78287. }
  78288. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78289. return "StereoscopicArcRotateCamera";
  78290. };
  78291. return StereoscopicArcRotateCamera;
  78292. }(BABYLON.ArcRotateCamera));
  78293. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78294. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78295. __extends(StereoscopicGamepadCamera, _super);
  78296. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78297. var _this = _super.call(this, name, position, scene) || this;
  78298. _this.interaxialDistance = interaxialDistance;
  78299. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78300. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78301. return _this;
  78302. }
  78303. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78304. return "StereoscopicGamepadCamera";
  78305. };
  78306. return StereoscopicGamepadCamera;
  78307. }(BABYLON.GamepadCamera));
  78308. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78309. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78310. __extends(StereoscopicUniversalCamera, _super);
  78311. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78312. var _this = _super.call(this, name, position, scene) || this;
  78313. _this.interaxialDistance = interaxialDistance;
  78314. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78315. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78316. return _this;
  78317. }
  78318. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78319. return "StereoscopicUniversalCamera";
  78320. };
  78321. return StereoscopicUniversalCamera;
  78322. }(BABYLON.UniversalCamera));
  78323. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78324. })(BABYLON || (BABYLON = {}));
  78325. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78326. var BABYLON;
  78327. (function (BABYLON) {
  78328. /**
  78329. * Helps to quickly add VR support to an existing scene.
  78330. * See http://doc.babylonjs.com/how_to/webvr_helper
  78331. */
  78332. var VRExperienceHelper = /** @class */ (function () {
  78333. /**
  78334. * Instantiates a VRExperienceHelper.
  78335. * Helps to quickly add VR support to an existing scene.
  78336. * @param scene The scene the VRExperienceHelper belongs to.
  78337. * @param webVROptions Options to modify the vr experience helper's behavior.
  78338. */
  78339. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78340. if (webVROptions === void 0) { webVROptions = {}; }
  78341. var _this = this;
  78342. this.webVROptions = webVROptions;
  78343. // Can the system support WebVR, even if a headset isn't plugged in?
  78344. this._webVRsupported = false;
  78345. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78346. this._webVRready = false;
  78347. // Are we waiting for the requestPresent callback to complete?
  78348. this._webVRrequesting = false;
  78349. // Are we presenting to the headset right now?
  78350. this._webVRpresenting = false;
  78351. // Are we presenting in the fullscreen fallback?
  78352. this._fullscreenVRpresenting = false;
  78353. /**
  78354. * Observable raised when entering VR.
  78355. */
  78356. this.onEnteringVRObservable = new BABYLON.Observable();
  78357. /**
  78358. * Observable raised when exiting VR.
  78359. */
  78360. this.onExitingVRObservable = new BABYLON.Observable();
  78361. /**
  78362. * Observable raised when controller mesh is loaded.
  78363. */
  78364. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78365. this._useCustomVRButton = false;
  78366. this._teleportationRequested = false;
  78367. this._teleportationEnabledOnLeftController = false;
  78368. this._teleportationEnabledOnRightController = false;
  78369. this._interactionsEnabledOnLeftController = false;
  78370. this._interactionsEnabledOnRightController = false;
  78371. this._leftControllerReady = false;
  78372. this._rightControllerReady = false;
  78373. this._floorMeshesCollection = [];
  78374. this._teleportationAllowed = false;
  78375. this._rotationAllowed = true;
  78376. this._teleportationRequestInitiated = false;
  78377. this._teleportationBackRequestInitiated = false;
  78378. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78379. this._rotationRightAsked = false;
  78380. this._rotationLeftAsked = false;
  78381. this._isDefaultTeleportationTarget = true;
  78382. this._teleportationFillColor = "#444444";
  78383. this._teleportationBorderColor = "#FFFFFF";
  78384. this._rotationAngle = 0;
  78385. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78386. this._padSensibilityUp = 0.65;
  78387. this._padSensibilityDown = 0.35;
  78388. /**
  78389. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78390. */
  78391. this.onNewMeshSelected = new BABYLON.Observable();
  78392. /**
  78393. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78394. */
  78395. this.onNewMeshPicked = new BABYLON.Observable();
  78396. /**
  78397. * Observable raised before camera teleportation
  78398. */
  78399. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78400. /**
  78401. * Observable raised after camera teleportation
  78402. */
  78403. this.onAfterCameraTeleport = new BABYLON.Observable();
  78404. /**
  78405. * Observable raised when current selected mesh gets unselected
  78406. */
  78407. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78408. /**
  78409. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78410. */
  78411. this.teleportationEnabled = true;
  78412. this._pointerDownOnMeshAsked = false;
  78413. this._isActionableMesh = false;
  78414. this._teleportationInitialized = false;
  78415. this._interactionsEnabled = false;
  78416. this._interactionsRequested = false;
  78417. this._displayGaze = true;
  78418. this._displayLaserPointer = true;
  78419. this._dpadPressed = true;
  78420. this._onResize = function () {
  78421. _this.moveButtonToBottomRight();
  78422. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78423. _this.exitVR();
  78424. }
  78425. };
  78426. this._onFullscreenChange = function () {
  78427. if (document.fullscreen !== undefined) {
  78428. _this._fullscreenVRpresenting = document.fullscreen;
  78429. }
  78430. else if (document.mozFullScreen !== undefined) {
  78431. _this._fullscreenVRpresenting = document.mozFullScreen;
  78432. }
  78433. else if (document.webkitIsFullScreen !== undefined) {
  78434. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78435. }
  78436. else if (document.msIsFullScreen !== undefined) {
  78437. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78438. }
  78439. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78440. _this.exitVR();
  78441. if (!_this._useCustomVRButton) {
  78442. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78443. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78444. }
  78445. }
  78446. };
  78447. this.beforeRender = function () {
  78448. _this._castRayAndSelectObject();
  78449. };
  78450. this._onNewGamepadConnected = function (gamepad) {
  78451. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78452. if (gamepad.leftStick) {
  78453. gamepad.onleftstickchanged(function (stickValues) {
  78454. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78455. // Listening to classic/xbox gamepad only if no VR controller is active
  78456. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78457. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78458. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78459. _this._checkTeleportWithRay(stickValues);
  78460. _this._checkTeleportBackwards(stickValues);
  78461. }
  78462. }
  78463. });
  78464. }
  78465. if (gamepad.rightStick) {
  78466. gamepad.onrightstickchanged(function (stickValues) {
  78467. if (_this._teleportationInitialized) {
  78468. _this._checkRotate(stickValues);
  78469. }
  78470. });
  78471. }
  78472. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78473. gamepad.onbuttondown(function (buttonPressed) {
  78474. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78475. _this._selectionPointerDown();
  78476. }
  78477. });
  78478. gamepad.onbuttonup(function (buttonPressed) {
  78479. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78480. _this._selectionPointerUp();
  78481. }
  78482. });
  78483. }
  78484. }
  78485. else {
  78486. var webVRController = gamepad;
  78487. _this._tryEnableInteractionOnController(webVRController);
  78488. }
  78489. };
  78490. // 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
  78491. this._tryEnableInteractionOnController = function (webVRController) {
  78492. if (webVRController.hand === "left") {
  78493. _this._leftControllerReady = true;
  78494. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78495. _this._enableInteractionOnController(webVRController);
  78496. }
  78497. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78498. _this._enableTeleportationOnController(webVRController);
  78499. }
  78500. }
  78501. if (webVRController.hand === "right") {
  78502. _this._rightControllerReady = true;
  78503. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78504. _this._enableInteractionOnController(webVRController);
  78505. }
  78506. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78507. _this._enableTeleportationOnController(webVRController);
  78508. }
  78509. }
  78510. };
  78511. this._onNewGamepadDisconnected = function (gamepad) {
  78512. if (gamepad instanceof BABYLON.WebVRController) {
  78513. if (gamepad.hand === "left") {
  78514. _this._interactionsEnabledOnLeftController = false;
  78515. _this._teleportationEnabledOnLeftController = false;
  78516. _this._leftControllerReady = false;
  78517. if (_this._leftLaserPointer) {
  78518. _this._leftLaserPointer.dispose();
  78519. }
  78520. }
  78521. if (gamepad.hand === "right") {
  78522. _this._interactionsEnabledOnRightController = false;
  78523. _this._teleportationEnabledOnRightController = false;
  78524. _this._rightControllerReady = false;
  78525. if (_this._rightLaserPointer) {
  78526. _this._rightLaserPointer.dispose();
  78527. }
  78528. }
  78529. }
  78530. };
  78531. this._workingVector = BABYLON.Vector3.Zero();
  78532. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78533. this._workingMatrix = BABYLON.Matrix.Identity();
  78534. this._scene = scene;
  78535. this._canvas = scene.getEngine().getRenderingCanvas();
  78536. // Parse options
  78537. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78538. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78539. }
  78540. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78541. webVROptions.createDeviceOrientationCamera = true;
  78542. }
  78543. if (webVROptions.defaultHeight === undefined) {
  78544. webVROptions.defaultHeight = 1.7;
  78545. }
  78546. if (webVROptions.useCustomVRButton) {
  78547. this._useCustomVRButton = true;
  78548. if (webVROptions.customVRButton) {
  78549. this._btnVR = webVROptions.customVRButton;
  78550. }
  78551. }
  78552. if (webVROptions.rayLength) {
  78553. this._rayLength = webVROptions.rayLength;
  78554. }
  78555. this._defaultHeight = webVROptions.defaultHeight;
  78556. // Set position
  78557. if (this._scene.activeCamera) {
  78558. this._position = this._scene.activeCamera.position.clone();
  78559. }
  78560. else {
  78561. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78562. }
  78563. // Set non-vr camera
  78564. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78565. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78566. // Copy data from existing camera
  78567. if (this._scene.activeCamera) {
  78568. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78569. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78570. // Set rotation from previous camera
  78571. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78572. var targetCamera = this._scene.activeCamera;
  78573. if (targetCamera.rotationQuaternion) {
  78574. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78575. }
  78576. else {
  78577. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78578. }
  78579. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78580. }
  78581. }
  78582. this._scene.activeCamera = this._deviceOrientationCamera;
  78583. if (this._canvas) {
  78584. this._scene.activeCamera.attachControl(this._canvas);
  78585. }
  78586. }
  78587. else {
  78588. this._existingCamera = this._scene.activeCamera;
  78589. }
  78590. // Create VR cameras
  78591. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78592. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78593. }
  78594. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78595. this._webVRCamera.useStandingMatrix();
  78596. // Create default button
  78597. if (!this._useCustomVRButton) {
  78598. this._btnVR = document.createElement("BUTTON");
  78599. this._btnVR.className = "babylonVRicon";
  78600. this._btnVR.id = "babylonVRiconbtn";
  78601. this._btnVR.title = "Click to switch to VR";
  78602. 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) }";
  78603. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78604. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78605. // css += ".babylonVRicon.vrdisplaysupported { }";
  78606. // css += ".babylonVRicon.vrdisplayready { }";
  78607. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78608. var style = document.createElement('style');
  78609. style.appendChild(document.createTextNode(css));
  78610. document.getElementsByTagName('head')[0].appendChild(style);
  78611. this.moveButtonToBottomRight();
  78612. }
  78613. // VR button click event
  78614. if (this._btnVR) {
  78615. this._btnVR.addEventListener("click", function () {
  78616. if (!_this.isInVRMode) {
  78617. _this.enterVR();
  78618. }
  78619. else {
  78620. _this.exitVR();
  78621. }
  78622. });
  78623. }
  78624. // Window events
  78625. window.addEventListener("resize", this._onResize);
  78626. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78627. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78628. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78629. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78630. // Display vr button when headset is connected
  78631. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78632. this.displayVRButton();
  78633. }
  78634. else {
  78635. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78636. if (e.vrDisplay) {
  78637. _this.displayVRButton();
  78638. }
  78639. });
  78640. }
  78641. // Exiting VR mode using 'ESC' key on desktop
  78642. this._onKeyDown = function (event) {
  78643. if (event.keyCode === 27 && _this.isInVRMode) {
  78644. _this.exitVR();
  78645. }
  78646. };
  78647. document.addEventListener("keydown", this._onKeyDown);
  78648. // Exiting VR mode double tapping the touch screen
  78649. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78650. if (_this.isInVRMode) {
  78651. _this.exitVR();
  78652. if (_this._fullscreenVRpresenting) {
  78653. _this._scene.getEngine().switchFullscreen(true);
  78654. }
  78655. }
  78656. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78657. // Listen for WebVR display changes
  78658. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78659. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78660. this._onVRRequestPresentStart = function () {
  78661. _this._webVRrequesting = true;
  78662. _this.updateButtonVisibility();
  78663. };
  78664. this._onVRRequestPresentComplete = function (success) {
  78665. _this._webVRrequesting = false;
  78666. _this.updateButtonVisibility();
  78667. };
  78668. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78669. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78670. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78671. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78672. scene.onDisposeObservable.add(function () {
  78673. _this.dispose();
  78674. });
  78675. // Gamepad connection events
  78676. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78677. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78678. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78679. this.updateButtonVisibility();
  78680. //create easing functions
  78681. this._circleEase = new BABYLON.CircleEase();
  78682. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78683. }
  78684. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78685. /** Return this.onEnteringVRObservable
  78686. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78687. */
  78688. get: function () {
  78689. return this.onEnteringVRObservable;
  78690. },
  78691. enumerable: true,
  78692. configurable: true
  78693. });
  78694. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78695. /** Return this.onExitingVRObservable
  78696. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78697. */
  78698. get: function () {
  78699. return this.onExitingVRObservable;
  78700. },
  78701. enumerable: true,
  78702. configurable: true
  78703. });
  78704. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78705. /** Return this.onControllerMeshLoadedObservable
  78706. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78707. */
  78708. get: function () {
  78709. return this.onControllerMeshLoadedObservable;
  78710. },
  78711. enumerable: true,
  78712. configurable: true
  78713. });
  78714. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78715. /**
  78716. * The mesh used to display where the user is going to teleport.
  78717. */
  78718. get: function () {
  78719. return this._teleportationTarget;
  78720. },
  78721. /**
  78722. * Sets the mesh to be used to display where the user is going to teleport.
  78723. */
  78724. set: function (value) {
  78725. if (value) {
  78726. value.name = "teleportationTarget";
  78727. this._isDefaultTeleportationTarget = false;
  78728. this._teleportationTarget = value;
  78729. }
  78730. },
  78731. enumerable: true,
  78732. configurable: true
  78733. });
  78734. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78735. /**
  78736. * The mesh used to display where the user is selecting.
  78737. */
  78738. get: function () {
  78739. return this._gazeTracker;
  78740. },
  78741. /**
  78742. * Sets the mesh to be used to display where the user is selecting.
  78743. */
  78744. set: function (value) {
  78745. if (value) {
  78746. this._gazeTracker = value;
  78747. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78748. this._gazeTracker.isPickable = false;
  78749. this._gazeTracker.isVisible = false;
  78750. }
  78751. },
  78752. enumerable: true,
  78753. configurable: true
  78754. });
  78755. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78756. /**
  78757. * If the ray of the gaze should be displayed.
  78758. */
  78759. get: function () {
  78760. return this._displayGaze;
  78761. },
  78762. /**
  78763. * Sets if the ray of the gaze should be displayed.
  78764. */
  78765. set: function (value) {
  78766. this._displayGaze = value;
  78767. if (!value) {
  78768. this._gazeTracker.isVisible = false;
  78769. }
  78770. },
  78771. enumerable: true,
  78772. configurable: true
  78773. });
  78774. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78775. /**
  78776. * If the ray of the LaserPointer should be displayed.
  78777. */
  78778. get: function () {
  78779. return this._displayLaserPointer;
  78780. },
  78781. /**
  78782. * Sets if the ray of the LaserPointer should be displayed.
  78783. */
  78784. set: function (value) {
  78785. this._displayLaserPointer = value;
  78786. if (!value) {
  78787. if (this._rightLaserPointer) {
  78788. this._rightLaserPointer.isVisible = false;
  78789. }
  78790. if (this._leftLaserPointer) {
  78791. this._leftLaserPointer.isVisible = false;
  78792. }
  78793. }
  78794. else {
  78795. if (this._rightLaserPointer) {
  78796. this._rightLaserPointer.isVisible = true;
  78797. }
  78798. else if (this._leftLaserPointer) {
  78799. this._leftLaserPointer.isVisible = true;
  78800. }
  78801. }
  78802. },
  78803. enumerable: true,
  78804. configurable: true
  78805. });
  78806. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78807. /**
  78808. * The deviceOrientationCamera used as the camera when not in VR.
  78809. */
  78810. get: function () {
  78811. return this._deviceOrientationCamera;
  78812. },
  78813. enumerable: true,
  78814. configurable: true
  78815. });
  78816. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78817. /**
  78818. * Based on the current WebVR support, returns the current VR camera used.
  78819. */
  78820. get: function () {
  78821. if (this._webVRready) {
  78822. return this._webVRCamera;
  78823. }
  78824. else {
  78825. return this._scene.activeCamera;
  78826. }
  78827. },
  78828. enumerable: true,
  78829. configurable: true
  78830. });
  78831. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78832. /**
  78833. * The webVRCamera which is used when in VR.
  78834. */
  78835. get: function () {
  78836. return this._webVRCamera;
  78837. },
  78838. enumerable: true,
  78839. configurable: true
  78840. });
  78841. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78842. /**
  78843. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78844. */
  78845. get: function () {
  78846. return this._vrDeviceOrientationCamera;
  78847. },
  78848. enumerable: true,
  78849. configurable: true
  78850. });
  78851. // Raised when one of the controller has loaded successfully its associated default mesh
  78852. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78853. this._tryEnableInteractionOnController(webVRController);
  78854. try {
  78855. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78856. }
  78857. catch (err) {
  78858. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78859. }
  78860. };
  78861. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78862. /**
  78863. * Gets a value indicating if we are currently in VR mode.
  78864. */
  78865. get: function () {
  78866. return this._webVRpresenting || this._fullscreenVRpresenting;
  78867. },
  78868. enumerable: true,
  78869. configurable: true
  78870. });
  78871. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78872. var vrDisplay = this._scene.getEngine().getVRDevice();
  78873. if (vrDisplay) {
  78874. var wasPresenting = this._webVRpresenting;
  78875. // A VR display is connected
  78876. this._webVRpresenting = vrDisplay.isPresenting;
  78877. if (wasPresenting && !this._webVRpresenting)
  78878. this.exitVR();
  78879. }
  78880. else {
  78881. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  78882. }
  78883. this.updateButtonVisibility();
  78884. };
  78885. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  78886. this._webVRsupported = eventArgs.vrSupported;
  78887. this._webVRready = !!eventArgs.vrDisplay;
  78888. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  78889. this.updateButtonVisibility();
  78890. };
  78891. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  78892. if (this._canvas && !this._useCustomVRButton) {
  78893. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  78894. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  78895. }
  78896. };
  78897. VRExperienceHelper.prototype.displayVRButton = function () {
  78898. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  78899. document.body.appendChild(this._btnVR);
  78900. this._btnVRDisplayed = true;
  78901. }
  78902. };
  78903. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  78904. if (!this._btnVR || this._useCustomVRButton) {
  78905. return;
  78906. }
  78907. this._btnVR.className = "babylonVRicon";
  78908. if (this.isInVRMode) {
  78909. this._btnVR.className += " vrdisplaypresenting";
  78910. }
  78911. else {
  78912. if (this._webVRready)
  78913. this._btnVR.className += " vrdisplayready";
  78914. if (this._webVRsupported)
  78915. this._btnVR.className += " vrdisplaysupported";
  78916. if (this._webVRrequesting)
  78917. this._btnVR.className += " vrdisplayrequesting";
  78918. }
  78919. };
  78920. /**
  78921. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  78922. * Otherwise, will use the fullscreen API.
  78923. */
  78924. VRExperienceHelper.prototype.enterVR = function () {
  78925. if (this.onEnteringVRObservable) {
  78926. try {
  78927. this.onEnteringVRObservable.notifyObservers(this);
  78928. }
  78929. catch (err) {
  78930. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  78931. }
  78932. }
  78933. if (this._scene.activeCamera) {
  78934. this._position = this._scene.activeCamera.position.clone();
  78935. // make sure that we return to the last active camera
  78936. this._existingCamera = this._scene.activeCamera;
  78937. }
  78938. if (this._webVRrequesting)
  78939. return;
  78940. // If WebVR is supported and a headset is connected
  78941. if (this._webVRready) {
  78942. if (!this._webVRpresenting) {
  78943. this._webVRCamera.position = this._position;
  78944. this._scene.activeCamera = this._webVRCamera;
  78945. }
  78946. }
  78947. else if (this._vrDeviceOrientationCamera) {
  78948. this._vrDeviceOrientationCamera.position = this._position;
  78949. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  78950. this._scene.getEngine().switchFullscreen(true);
  78951. this.updateButtonVisibility();
  78952. }
  78953. if (this._scene.activeCamera && this._canvas) {
  78954. this._scene.activeCamera.attachControl(this._canvas);
  78955. }
  78956. if (this._interactionsEnabled) {
  78957. this._scene.registerBeforeRender(this.beforeRender);
  78958. }
  78959. };
  78960. /**
  78961. * Attempt to exit VR, or fullscreen.
  78962. */
  78963. VRExperienceHelper.prototype.exitVR = function () {
  78964. if (this.onExitingVRObservable) {
  78965. try {
  78966. this.onExitingVRObservable.notifyObservers(this);
  78967. }
  78968. catch (err) {
  78969. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  78970. }
  78971. }
  78972. if (this._webVRpresenting) {
  78973. this._scene.getEngine().disableVR();
  78974. }
  78975. if (this._scene.activeCamera) {
  78976. this._position = this._scene.activeCamera.position.clone();
  78977. }
  78978. if (this._deviceOrientationCamera) {
  78979. this._deviceOrientationCamera.position = this._position;
  78980. this._scene.activeCamera = this._deviceOrientationCamera;
  78981. if (this._canvas) {
  78982. this._scene.activeCamera.attachControl(this._canvas);
  78983. }
  78984. }
  78985. else if (this._existingCamera) {
  78986. this._existingCamera.position = this._position;
  78987. this._scene.activeCamera = this._existingCamera;
  78988. }
  78989. this.updateButtonVisibility();
  78990. if (this._interactionsEnabled) {
  78991. this._scene.unregisterBeforeRender(this.beforeRender);
  78992. }
  78993. };
  78994. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  78995. /**
  78996. * The position of the vr experience helper.
  78997. */
  78998. get: function () {
  78999. return this._position;
  79000. },
  79001. /**
  79002. * Sets the position of the vr experience helper.
  79003. */
  79004. set: function (value) {
  79005. this._position = value;
  79006. if (this._scene.activeCamera) {
  79007. this._scene.activeCamera.position = value;
  79008. }
  79009. },
  79010. enumerable: true,
  79011. configurable: true
  79012. });
  79013. /**
  79014. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79015. */
  79016. VRExperienceHelper.prototype.enableInteractions = function () {
  79017. var _this = this;
  79018. if (!this._interactionsEnabled) {
  79019. this._interactionsRequested = true;
  79020. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79021. this._enableInteractionOnController(this._webVRCamera.leftController);
  79022. }
  79023. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79024. this._enableInteractionOnController(this._webVRCamera.rightController);
  79025. }
  79026. if (!this._gazeTracker) {
  79027. this._createGazeTracker();
  79028. }
  79029. this.raySelectionPredicate = function (mesh) {
  79030. return mesh.isVisible;
  79031. };
  79032. this.meshSelectionPredicate = function (mesh) {
  79033. return true;
  79034. };
  79035. this._raySelectionPredicate = function (mesh) {
  79036. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79037. && mesh.name.indexOf("teleportationTarget") === -1
  79038. && mesh.name.indexOf("torusTeleportation") === -1
  79039. && mesh.name.indexOf("laserPointer") === -1)) {
  79040. return _this.raySelectionPredicate(mesh);
  79041. }
  79042. return false;
  79043. };
  79044. this._interactionsEnabled = true;
  79045. }
  79046. };
  79047. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79048. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79049. if (this._floorMeshesCollection[i].id === mesh.id) {
  79050. return true;
  79051. }
  79052. }
  79053. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79054. return true;
  79055. }
  79056. return false;
  79057. };
  79058. /**
  79059. * Adds a floor mesh to be used for teleportation.
  79060. * @param floorMesh the mesh to be used for teleportation.
  79061. */
  79062. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79063. if (!this._floorMeshesCollection) {
  79064. return;
  79065. }
  79066. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79067. return;
  79068. }
  79069. this._floorMeshesCollection.push(floorMesh);
  79070. };
  79071. /**
  79072. * Removes a floor mesh from being used for teleportation.
  79073. * @param floorMesh the mesh to be removed.
  79074. */
  79075. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79076. if (!this._floorMeshesCollection) {
  79077. return;
  79078. }
  79079. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79080. if (meshIndex !== -1) {
  79081. this._floorMeshesCollection.splice(meshIndex, 1);
  79082. }
  79083. };
  79084. /**
  79085. * Enables interactions and teleportation using the VR controllers and gaze.
  79086. * @param vrTeleportationOptions options to modify teleportation behavior.
  79087. */
  79088. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79089. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79090. if (!this._teleportationInitialized) {
  79091. this._teleportationRequested = true;
  79092. this.enableInteractions();
  79093. if (vrTeleportationOptions.floorMeshName) {
  79094. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79095. }
  79096. if (vrTeleportationOptions.floorMeshes) {
  79097. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79098. }
  79099. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79100. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79101. }
  79102. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79103. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79104. }
  79105. // Creates an image processing post process for the vignette not relying
  79106. // on the main scene configuration for image processing to reduce setup and spaces
  79107. // (gamma/linear) conflicts.
  79108. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79109. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79110. imageProcessingConfiguration.vignetteEnabled = true;
  79111. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79112. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79113. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79114. this._teleportationInitialized = true;
  79115. if (this._isDefaultTeleportationTarget) {
  79116. this._createTeleportationCircles();
  79117. }
  79118. }
  79119. };
  79120. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79121. var _this = this;
  79122. var controllerMesh = webVRController.mesh;
  79123. if (controllerMesh) {
  79124. var makeNotPick = function (root) {
  79125. root.name += " laserPointer";
  79126. root.getChildMeshes().forEach(function (c) {
  79127. makeNotPick(c);
  79128. });
  79129. };
  79130. makeNotPick(controllerMesh);
  79131. var childMeshes = controllerMesh.getChildMeshes();
  79132. for (var i = 0; i < childMeshes.length; i++) {
  79133. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79134. controllerMesh = childMeshes[i];
  79135. break;
  79136. }
  79137. }
  79138. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79139. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79140. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79141. laserPointerMaterial.alpha = 0.6;
  79142. laserPointer.material = laserPointerMaterial;
  79143. laserPointer.rotation.x = Math.PI / 2;
  79144. laserPointer.parent = controllerMesh;
  79145. laserPointer.position.z = -0.5;
  79146. laserPointer.isVisible = false;
  79147. if (webVRController.hand === "left") {
  79148. this._leftLaserPointer = laserPointer;
  79149. this._interactionsEnabledOnLeftController = true;
  79150. if (!this._rightLaserPointer) {
  79151. this._leftLaserPointer.isVisible = true;
  79152. }
  79153. }
  79154. else {
  79155. this._rightLaserPointer = laserPointer;
  79156. this._interactionsEnabledOnRightController = true;
  79157. if (!this._leftLaserPointer) {
  79158. this._rightLaserPointer.isVisible = true;
  79159. }
  79160. }
  79161. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79162. // Enabling / disabling laserPointer
  79163. if (_this._displayLaserPointer && stateObject.value === 1) {
  79164. laserPointer.isVisible = !laserPointer.isVisible;
  79165. // Laser pointer can only be active on left or right, not both at the same time
  79166. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79167. _this._rightLaserPointer.isVisible = false;
  79168. }
  79169. else if (_this._leftLaserPointer) {
  79170. _this._leftLaserPointer.isVisible = false;
  79171. }
  79172. }
  79173. });
  79174. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79175. if (!_this._pointerDownOnMeshAsked) {
  79176. if (stateObject.value > _this._padSensibilityUp) {
  79177. _this._selectionPointerDown();
  79178. }
  79179. }
  79180. else if (stateObject.value < _this._padSensibilityDown) {
  79181. _this._selectionPointerUp();
  79182. }
  79183. });
  79184. }
  79185. };
  79186. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79187. if (webVRController === void 0) { webVRController = null; }
  79188. if (!this._teleportationRequestInitiated) {
  79189. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79190. if (webVRController) {
  79191. // If laser pointer wasn't enabled yet
  79192. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79193. this._leftLaserPointer.isVisible = true;
  79194. if (this._rightLaserPointer) {
  79195. this._rightLaserPointer.isVisible = false;
  79196. }
  79197. }
  79198. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79199. this._rightLaserPointer.isVisible = true;
  79200. if (this._leftLaserPointer) {
  79201. this._leftLaserPointer.isVisible = false;
  79202. }
  79203. }
  79204. }
  79205. this._teleportationRequestInitiated = true;
  79206. }
  79207. }
  79208. else {
  79209. // Listening to the proper controller values changes to confirm teleportation
  79210. if (webVRController == null
  79211. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79212. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79213. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79214. if (this._teleportationAllowed) {
  79215. this._teleportationAllowed = false;
  79216. this._teleportCamera();
  79217. }
  79218. this._teleportationRequestInitiated = false;
  79219. }
  79220. }
  79221. }
  79222. };
  79223. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79224. this._pointerDownOnMeshAsked = true;
  79225. if (this._currentMeshSelected && this._currentHit) {
  79226. this._scene.simulatePointerDown(this._currentHit);
  79227. }
  79228. };
  79229. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79230. if (this._currentMeshSelected && this._currentHit) {
  79231. this._scene.simulatePointerUp(this._currentHit);
  79232. }
  79233. this._pointerDownOnMeshAsked = false;
  79234. };
  79235. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79236. // Only rotate when user is not currently selecting a teleportation location
  79237. if (this._teleportationRequestInitiated) {
  79238. return;
  79239. }
  79240. if (!this._rotationLeftAsked) {
  79241. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79242. this._rotationLeftAsked = true;
  79243. if (this._rotationAllowed) {
  79244. this._rotateCamera(false);
  79245. }
  79246. }
  79247. }
  79248. else {
  79249. if (stateObject.x > -this._padSensibilityDown) {
  79250. this._rotationLeftAsked = false;
  79251. }
  79252. }
  79253. if (!this._rotationRightAsked) {
  79254. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79255. this._rotationRightAsked = true;
  79256. if (this._rotationAllowed) {
  79257. this._rotateCamera(true);
  79258. }
  79259. }
  79260. }
  79261. else {
  79262. if (stateObject.x < this._padSensibilityDown) {
  79263. this._rotationRightAsked = false;
  79264. }
  79265. }
  79266. };
  79267. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79268. // Only teleport backwards when user is not currently selecting a teleportation location
  79269. if (this._teleportationRequestInitiated) {
  79270. return;
  79271. }
  79272. // Teleport backwards
  79273. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79274. if (!this._teleportationBackRequestInitiated) {
  79275. if (!this.currentVRCamera) {
  79276. return;
  79277. }
  79278. // Get rotation and position of the current camera
  79279. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79280. var position = this.currentVRCamera.position;
  79281. // If the camera has device position, use that instead
  79282. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79283. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79284. position = this.currentVRCamera.devicePosition;
  79285. }
  79286. // Get matrix with only the y rotation of the device rotation
  79287. rotation.toEulerAnglesToRef(this._workingVector);
  79288. this._workingVector.z = 0;
  79289. this._workingVector.x = 0;
  79290. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79291. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79292. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79293. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79294. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79295. var ray = new BABYLON.Ray(position, this._workingVector);
  79296. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79297. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79298. this._teleportCamera(hit.pickedPoint);
  79299. }
  79300. this._teleportationBackRequestInitiated = true;
  79301. }
  79302. }
  79303. else {
  79304. this._teleportationBackRequestInitiated = false;
  79305. }
  79306. };
  79307. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79308. var _this = this;
  79309. var controllerMesh = webVRController.mesh;
  79310. if (controllerMesh) {
  79311. if (webVRController.hand === "left") {
  79312. if (!this._interactionsEnabledOnLeftController) {
  79313. this._enableInteractionOnController(webVRController);
  79314. }
  79315. this._teleportationEnabledOnLeftController = true;
  79316. }
  79317. else {
  79318. if (!this._interactionsEnabledOnRightController) {
  79319. this._enableInteractionOnController(webVRController);
  79320. }
  79321. this._teleportationEnabledOnRightController = true;
  79322. }
  79323. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79324. this._dpadPressed = false;
  79325. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79326. _this._dpadPressed = stateObject.pressed;
  79327. if (!_this._dpadPressed) {
  79328. _this._rotationLeftAsked = false;
  79329. _this._rotationRightAsked = false;
  79330. _this._teleportationBackRequestInitiated = false;
  79331. }
  79332. });
  79333. }
  79334. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79335. if (_this.teleportationEnabled) {
  79336. _this._checkTeleportBackwards(stateObject);
  79337. _this._checkTeleportWithRay(stateObject, webVRController);
  79338. }
  79339. _this._checkRotate(stateObject);
  79340. });
  79341. }
  79342. };
  79343. // Gaze support used to point to teleport or to interact with an object
  79344. VRExperienceHelper.prototype._createGazeTracker = function () {
  79345. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79346. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79347. this._gazeTracker.isPickable = false;
  79348. this._gazeTracker.isVisible = false;
  79349. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79350. targetMat.specularColor = BABYLON.Color3.Black();
  79351. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79352. targetMat.backFaceCulling = false;
  79353. this._gazeTracker.material = targetMat;
  79354. };
  79355. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79356. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79357. this._teleportationTarget.isPickable = false;
  79358. var length = 512;
  79359. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79360. dynamicTexture.hasAlpha = true;
  79361. var context = dynamicTexture.getContext();
  79362. var centerX = length / 2;
  79363. var centerY = length / 2;
  79364. var radius = 200;
  79365. context.beginPath();
  79366. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79367. context.fillStyle = this._teleportationFillColor;
  79368. context.fill();
  79369. context.lineWidth = 10;
  79370. context.strokeStyle = this._teleportationBorderColor;
  79371. context.stroke();
  79372. context.closePath();
  79373. dynamicTexture.update();
  79374. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79375. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79376. this._teleportationTarget.material = teleportationCircleMaterial;
  79377. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79378. torus.isPickable = false;
  79379. torus.parent = this._teleportationTarget;
  79380. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79381. var keys = [];
  79382. keys.push({
  79383. frame: 0,
  79384. value: 0
  79385. });
  79386. keys.push({
  79387. frame: 30,
  79388. value: 0.4
  79389. });
  79390. keys.push({
  79391. frame: 60,
  79392. value: 0
  79393. });
  79394. animationInnerCircle.setKeys(keys);
  79395. var easingFunction = new BABYLON.SineEase();
  79396. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79397. animationInnerCircle.setEasingFunction(easingFunction);
  79398. torus.animations = [];
  79399. torus.animations.push(animationInnerCircle);
  79400. this._scene.beginAnimation(torus, 0, 60, true);
  79401. this._hideTeleportationTarget();
  79402. };
  79403. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79404. if (this._teleportationInitialized) {
  79405. this._teleportationTarget.isVisible = true;
  79406. if (this._isDefaultTeleportationTarget) {
  79407. this._teleportationTarget.getChildren()[0].isVisible = true;
  79408. }
  79409. }
  79410. };
  79411. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79412. if (this._teleportationInitialized) {
  79413. this._teleportationTarget.isVisible = false;
  79414. if (this._isDefaultTeleportationTarget) {
  79415. this._teleportationTarget.getChildren()[0].isVisible = false;
  79416. }
  79417. }
  79418. };
  79419. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79420. var _this = this;
  79421. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79422. return;
  79423. }
  79424. if (right) {
  79425. this._rotationAngle++;
  79426. }
  79427. else {
  79428. this._rotationAngle--;
  79429. }
  79430. this.currentVRCamera.animations = [];
  79431. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79432. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79433. var animationRotationKeys = [];
  79434. animationRotationKeys.push({
  79435. frame: 0,
  79436. value: this.currentVRCamera.rotationQuaternion
  79437. });
  79438. animationRotationKeys.push({
  79439. frame: 6,
  79440. value: target
  79441. });
  79442. animationRotation.setKeys(animationRotationKeys);
  79443. animationRotation.setEasingFunction(this._circleEase);
  79444. this.currentVRCamera.animations.push(animationRotation);
  79445. this._postProcessMove.animations = [];
  79446. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79447. var vignetteWeightKeys = [];
  79448. vignetteWeightKeys.push({
  79449. frame: 0,
  79450. value: 0
  79451. });
  79452. vignetteWeightKeys.push({
  79453. frame: 3,
  79454. value: 4
  79455. });
  79456. vignetteWeightKeys.push({
  79457. frame: 6,
  79458. value: 0
  79459. });
  79460. animationPP.setKeys(vignetteWeightKeys);
  79461. animationPP.setEasingFunction(this._circleEase);
  79462. this._postProcessMove.animations.push(animationPP);
  79463. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79464. var vignetteStretchKeys = [];
  79465. vignetteStretchKeys.push({
  79466. frame: 0,
  79467. value: 0
  79468. });
  79469. vignetteStretchKeys.push({
  79470. frame: 3,
  79471. value: 10
  79472. });
  79473. vignetteStretchKeys.push({
  79474. frame: 6,
  79475. value: 0
  79476. });
  79477. animationPP2.setKeys(vignetteStretchKeys);
  79478. animationPP2.setEasingFunction(this._circleEase);
  79479. this._postProcessMove.animations.push(animationPP2);
  79480. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79481. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79482. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79483. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79484. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79485. });
  79486. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79487. };
  79488. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79489. if (hit.pickedPoint) {
  79490. this._teleportationAllowed = true;
  79491. if (this._teleportationRequestInitiated) {
  79492. this._displayTeleportationTarget();
  79493. }
  79494. else {
  79495. this._hideTeleportationTarget();
  79496. }
  79497. this._haloCenter.copyFrom(hit.pickedPoint);
  79498. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79499. var pickNormal = hit.getNormal(true, false);
  79500. if (pickNormal) {
  79501. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79502. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79503. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79504. }
  79505. this._teleportationTarget.position.y += 0.1;
  79506. }
  79507. };
  79508. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79509. var _this = this;
  79510. if (location === void 0) { location = null; }
  79511. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79512. return;
  79513. }
  79514. if (!location) {
  79515. location = this._haloCenter;
  79516. }
  79517. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79518. // offset of the headset from the anchor.
  79519. if (this.webVRCamera.leftCamera) {
  79520. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79521. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79522. location.subtractToRef(this._workingVector, this._workingVector);
  79523. }
  79524. else {
  79525. this._workingVector.copyFrom(location);
  79526. }
  79527. // Add height to account for user's height offset
  79528. if (this.isInVRMode) {
  79529. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79530. }
  79531. else {
  79532. this._workingVector.y += this._defaultHeight;
  79533. }
  79534. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79535. // Create animation from the camera's position to the new location
  79536. this.currentVRCamera.animations = [];
  79537. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79538. var animationCameraTeleportationKeys = [{
  79539. frame: 0,
  79540. value: this.currentVRCamera.position
  79541. },
  79542. {
  79543. frame: 11,
  79544. value: this._workingVector
  79545. }
  79546. ];
  79547. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79548. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79549. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79550. this._postProcessMove.animations = [];
  79551. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79552. var vignetteWeightKeys = [];
  79553. vignetteWeightKeys.push({
  79554. frame: 0,
  79555. value: 0
  79556. });
  79557. vignetteWeightKeys.push({
  79558. frame: 5,
  79559. value: 8
  79560. });
  79561. vignetteWeightKeys.push({
  79562. frame: 11,
  79563. value: 0
  79564. });
  79565. animationPP.setKeys(vignetteWeightKeys);
  79566. this._postProcessMove.animations.push(animationPP);
  79567. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79568. var vignetteStretchKeys = [];
  79569. vignetteStretchKeys.push({
  79570. frame: 0,
  79571. value: 0
  79572. });
  79573. vignetteStretchKeys.push({
  79574. frame: 5,
  79575. value: 10
  79576. });
  79577. vignetteStretchKeys.push({
  79578. frame: 11,
  79579. value: 0
  79580. });
  79581. animationPP2.setKeys(vignetteStretchKeys);
  79582. this._postProcessMove.animations.push(animationPP2);
  79583. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79584. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79585. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79586. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79587. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79588. });
  79589. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79590. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79591. });
  79592. };
  79593. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79594. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79595. return;
  79596. }
  79597. var ray;
  79598. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79599. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79600. }
  79601. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79602. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79603. }
  79604. else {
  79605. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79606. }
  79607. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79608. // Moving the gazeTracker on the mesh face targetted
  79609. if (hit && hit.pickedPoint) {
  79610. if (this._displayGaze) {
  79611. var multiplier = 1;
  79612. this._gazeTracker.isVisible = true;
  79613. if (this._isActionableMesh) {
  79614. multiplier = 3;
  79615. }
  79616. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79617. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79618. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79619. var pickNormal = hit.getNormal();
  79620. // To avoid z-fighting
  79621. var deltaFighting = 0.002;
  79622. if (pickNormal) {
  79623. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79624. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79625. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79626. }
  79627. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79628. if (this._gazeTracker.position.x < 0) {
  79629. this._gazeTracker.position.x += deltaFighting;
  79630. }
  79631. else {
  79632. this._gazeTracker.position.x -= deltaFighting;
  79633. }
  79634. if (this._gazeTracker.position.y < 0) {
  79635. this._gazeTracker.position.y += deltaFighting;
  79636. }
  79637. else {
  79638. this._gazeTracker.position.y -= deltaFighting;
  79639. }
  79640. if (this._gazeTracker.position.z < 0) {
  79641. this._gazeTracker.position.z += deltaFighting;
  79642. }
  79643. else {
  79644. this._gazeTracker.position.z -= deltaFighting;
  79645. }
  79646. }
  79647. // Changing the size of the laser pointer based on the distance from the targetted point
  79648. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79649. this._rightLaserPointer.scaling.y = hit.distance;
  79650. this._rightLaserPointer.position.z = -hit.distance / 2;
  79651. }
  79652. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79653. this._leftLaserPointer.scaling.y = hit.distance;
  79654. this._leftLaserPointer.position.z = -hit.distance / 2;
  79655. }
  79656. }
  79657. else {
  79658. this._gazeTracker.isVisible = false;
  79659. }
  79660. if (hit && hit.pickedMesh) {
  79661. this._currentHit = hit;
  79662. if (this._pointerDownOnMeshAsked) {
  79663. this._scene.simulatePointerMove(this._currentHit);
  79664. }
  79665. // The object selected is the floor, we're in a teleportation scenario
  79666. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79667. // Moving the teleportation area to this targetted point
  79668. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79669. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79670. this._notifySelectedMeshUnselected();
  79671. }
  79672. this._currentMeshSelected = null;
  79673. this._moveTeleportationSelectorTo(hit);
  79674. return;
  79675. }
  79676. // If not, we're in a selection scenario
  79677. this._hideTeleportationTarget();
  79678. this._teleportationAllowed = false;
  79679. if (hit.pickedMesh !== this._currentMeshSelected) {
  79680. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79681. this.onNewMeshPicked.notifyObservers(hit);
  79682. this._currentMeshSelected = hit.pickedMesh;
  79683. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79684. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79685. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79686. this._isActionableMesh = true;
  79687. }
  79688. else {
  79689. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79690. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79691. this._isActionableMesh = false;
  79692. }
  79693. try {
  79694. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79695. }
  79696. catch (err) {
  79697. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79698. }
  79699. }
  79700. else {
  79701. this._notifySelectedMeshUnselected();
  79702. this._currentMeshSelected = null;
  79703. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79704. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79705. }
  79706. }
  79707. }
  79708. else {
  79709. this._currentHit = null;
  79710. this._notifySelectedMeshUnselected();
  79711. this._currentMeshSelected = null;
  79712. this._teleportationAllowed = false;
  79713. this._hideTeleportationTarget();
  79714. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79715. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79716. }
  79717. };
  79718. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79719. if (this._currentMeshSelected) {
  79720. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79721. }
  79722. };
  79723. /**
  79724. * Sets the color of the laser ray from the vr controllers.
  79725. * @param color new color for the ray.
  79726. */
  79727. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79728. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79729. this._leftLaserPointer.material.emissiveColor = color;
  79730. }
  79731. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79732. this._rightLaserPointer.material.emissiveColor = color;
  79733. }
  79734. };
  79735. /**
  79736. * Sets the color of the ray from the vr headsets gaze.
  79737. * @param color new color for the ray.
  79738. */
  79739. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79740. if (this._gazeTracker.material) {
  79741. this._gazeTracker.material.emissiveColor = color;
  79742. }
  79743. };
  79744. /**
  79745. * Exits VR and disposes of the vr experience helper
  79746. */
  79747. VRExperienceHelper.prototype.dispose = function () {
  79748. if (this.isInVRMode) {
  79749. this.exitVR();
  79750. }
  79751. if (this._passProcessMove) {
  79752. this._passProcessMove.dispose();
  79753. }
  79754. if (this._postProcessMove) {
  79755. this._postProcessMove.dispose();
  79756. }
  79757. if (this._webVRCamera) {
  79758. this._webVRCamera.dispose();
  79759. }
  79760. if (this._vrDeviceOrientationCamera) {
  79761. this._vrDeviceOrientationCamera.dispose();
  79762. }
  79763. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79764. document.body.removeChild(this._btnVR);
  79765. }
  79766. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79767. this._deviceOrientationCamera.dispose();
  79768. }
  79769. if (this._gazeTracker) {
  79770. this._gazeTracker.dispose();
  79771. }
  79772. if (this._teleportationTarget) {
  79773. this._teleportationTarget.dispose();
  79774. }
  79775. this._floorMeshesCollection = [];
  79776. document.removeEventListener("keydown", this._onKeyDown);
  79777. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79778. window.removeEventListener("resize", this._onResize);
  79779. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79780. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79781. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79782. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79783. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79784. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79785. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79786. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79787. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79788. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79789. this._scene.unregisterBeforeRender(this.beforeRender);
  79790. };
  79791. /**
  79792. * Gets the name of the VRExperienceHelper class
  79793. * @returns "VRExperienceHelper"
  79794. */
  79795. VRExperienceHelper.prototype.getClassName = function () {
  79796. return "VRExperienceHelper";
  79797. };
  79798. return VRExperienceHelper;
  79799. }());
  79800. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79801. })(BABYLON || (BABYLON = {}));
  79802. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79803. // Mainly based on these 2 articles :
  79804. // 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
  79805. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79806. var BABYLON;
  79807. (function (BABYLON) {
  79808. var JoystickAxis;
  79809. (function (JoystickAxis) {
  79810. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79811. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79812. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79813. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79814. var VirtualJoystick = /** @class */ (function () {
  79815. function VirtualJoystick(leftJoystick) {
  79816. var _this = this;
  79817. if (leftJoystick) {
  79818. this._leftJoystick = true;
  79819. }
  79820. else {
  79821. this._leftJoystick = false;
  79822. }
  79823. VirtualJoystick._globalJoystickIndex++;
  79824. // By default left & right arrow keys are moving the X
  79825. // and up & down keys are moving the Y
  79826. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79827. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79828. this.reverseLeftRight = false;
  79829. this.reverseUpDown = false;
  79830. // collections of pointers
  79831. this._touches = new BABYLON.StringDictionary();
  79832. this.deltaPosition = BABYLON.Vector3.Zero();
  79833. this._joystickSensibility = 25;
  79834. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79835. this._onResize = function (evt) {
  79836. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79837. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79838. if (VirtualJoystick.vjCanvas) {
  79839. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79840. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79841. }
  79842. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79843. };
  79844. // injecting a canvas element on top of the canvas 3D game
  79845. if (!VirtualJoystick.vjCanvas) {
  79846. window.addEventListener("resize", this._onResize, false);
  79847. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79848. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79849. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79850. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79851. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79852. VirtualJoystick.vjCanvas.style.width = "100%";
  79853. VirtualJoystick.vjCanvas.style.height = "100%";
  79854. VirtualJoystick.vjCanvas.style.position = "absolute";
  79855. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79856. VirtualJoystick.vjCanvas.style.top = "0px";
  79857. VirtualJoystick.vjCanvas.style.left = "0px";
  79858. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79859. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79860. // Support for jQuery PEP polyfill
  79861. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79862. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79863. if (!context) {
  79864. throw new Error("Unable to create canvas for virtual joystick");
  79865. }
  79866. VirtualJoystick.vjCanvasContext = context;
  79867. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79868. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79869. document.body.appendChild(VirtualJoystick.vjCanvas);
  79870. }
  79871. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79872. this.pressed = false;
  79873. // default joystick color
  79874. this._joystickColor = "cyan";
  79875. this._joystickPointerID = -1;
  79876. // current joystick position
  79877. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  79878. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  79879. // origin joystick position
  79880. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  79881. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  79882. this._onPointerDownHandlerRef = function (evt) {
  79883. _this._onPointerDown(evt);
  79884. };
  79885. this._onPointerMoveHandlerRef = function (evt) {
  79886. _this._onPointerMove(evt);
  79887. };
  79888. this._onPointerUpHandlerRef = function (evt) {
  79889. _this._onPointerUp(evt);
  79890. };
  79891. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  79892. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  79893. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  79894. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  79895. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  79896. evt.preventDefault(); // Disables system menu
  79897. }, false);
  79898. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79899. }
  79900. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  79901. this._joystickSensibility = newJoystickSensibility;
  79902. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79903. };
  79904. VirtualJoystick.prototype._onPointerDown = function (e) {
  79905. var positionOnScreenCondition;
  79906. e.preventDefault();
  79907. if (this._leftJoystick === true) {
  79908. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  79909. }
  79910. else {
  79911. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  79912. }
  79913. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  79914. // First contact will be dedicated to the virtual joystick
  79915. this._joystickPointerID = e.pointerId;
  79916. this._joystickPointerStartPos.x = e.clientX;
  79917. this._joystickPointerStartPos.y = e.clientY;
  79918. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  79919. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  79920. this._deltaJoystickVector.x = 0;
  79921. this._deltaJoystickVector.y = 0;
  79922. this.pressed = true;
  79923. this._touches.add(e.pointerId.toString(), e);
  79924. }
  79925. else {
  79926. // You can only trigger the action buttons with a joystick declared
  79927. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  79928. this._action();
  79929. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  79930. }
  79931. }
  79932. };
  79933. VirtualJoystick.prototype._onPointerMove = function (e) {
  79934. // If the current pointer is the one associated to the joystick (first touch contact)
  79935. if (this._joystickPointerID == e.pointerId) {
  79936. this._joystickPointerPos.x = e.clientX;
  79937. this._joystickPointerPos.y = e.clientY;
  79938. this._deltaJoystickVector = this._joystickPointerPos.clone();
  79939. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  79940. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  79941. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  79942. switch (this._axisTargetedByLeftAndRight) {
  79943. case JoystickAxis.X:
  79944. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  79945. break;
  79946. case JoystickAxis.Y:
  79947. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  79948. break;
  79949. case JoystickAxis.Z:
  79950. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  79951. break;
  79952. }
  79953. var directionUpDown = this.reverseUpDown ? 1 : -1;
  79954. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  79955. switch (this._axisTargetedByUpAndDown) {
  79956. case JoystickAxis.X:
  79957. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  79958. break;
  79959. case JoystickAxis.Y:
  79960. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  79961. break;
  79962. case JoystickAxis.Z:
  79963. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  79964. break;
  79965. }
  79966. }
  79967. else {
  79968. var data = this._touches.get(e.pointerId.toString());
  79969. if (data) {
  79970. data.x = e.clientX;
  79971. data.y = e.clientY;
  79972. }
  79973. }
  79974. };
  79975. VirtualJoystick.prototype._onPointerUp = function (e) {
  79976. if (this._joystickPointerID == e.pointerId) {
  79977. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  79978. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  79979. this._joystickPointerID = -1;
  79980. this.pressed = false;
  79981. }
  79982. else {
  79983. var touch = this._touches.get(e.pointerId.toString());
  79984. if (touch) {
  79985. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  79986. }
  79987. }
  79988. this._deltaJoystickVector.x = 0;
  79989. this._deltaJoystickVector.y = 0;
  79990. this._touches.remove(e.pointerId.toString());
  79991. };
  79992. /**
  79993. * Change the color of the virtual joystick
  79994. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  79995. */
  79996. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  79997. this._joystickColor = newColor;
  79998. };
  79999. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80000. this._action = action;
  80001. };
  80002. // Define which axis you'd like to control for left & right
  80003. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80004. switch (axis) {
  80005. case JoystickAxis.X:
  80006. case JoystickAxis.Y:
  80007. case JoystickAxis.Z:
  80008. this._axisTargetedByLeftAndRight = axis;
  80009. break;
  80010. default:
  80011. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80012. break;
  80013. }
  80014. };
  80015. // Define which axis you'd like to control for up & down
  80016. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80017. switch (axis) {
  80018. case JoystickAxis.X:
  80019. case JoystickAxis.Y:
  80020. case JoystickAxis.Z:
  80021. this._axisTargetedByUpAndDown = axis;
  80022. break;
  80023. default:
  80024. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80025. break;
  80026. }
  80027. };
  80028. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80029. var _this = this;
  80030. if (this.pressed) {
  80031. this._touches.forEach(function (key, touch) {
  80032. if (touch.pointerId === _this._joystickPointerID) {
  80033. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80034. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80035. VirtualJoystick.vjCanvasContext.beginPath();
  80036. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80037. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80038. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80039. VirtualJoystick.vjCanvasContext.stroke();
  80040. VirtualJoystick.vjCanvasContext.closePath();
  80041. VirtualJoystick.vjCanvasContext.beginPath();
  80042. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80043. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80044. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80045. VirtualJoystick.vjCanvasContext.stroke();
  80046. VirtualJoystick.vjCanvasContext.closePath();
  80047. VirtualJoystick.vjCanvasContext.beginPath();
  80048. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80049. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80050. VirtualJoystick.vjCanvasContext.stroke();
  80051. VirtualJoystick.vjCanvasContext.closePath();
  80052. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80053. }
  80054. else {
  80055. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80056. VirtualJoystick.vjCanvasContext.beginPath();
  80057. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80058. VirtualJoystick.vjCanvasContext.beginPath();
  80059. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80060. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80061. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80062. VirtualJoystick.vjCanvasContext.stroke();
  80063. VirtualJoystick.vjCanvasContext.closePath();
  80064. touch.prevX = touch.x;
  80065. touch.prevY = touch.y;
  80066. }
  80067. ;
  80068. });
  80069. }
  80070. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80071. };
  80072. VirtualJoystick.prototype.releaseCanvas = function () {
  80073. if (VirtualJoystick.vjCanvas) {
  80074. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80075. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80076. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80077. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80078. window.removeEventListener("resize", this._onResize);
  80079. document.body.removeChild(VirtualJoystick.vjCanvas);
  80080. VirtualJoystick.vjCanvas = null;
  80081. }
  80082. };
  80083. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80084. VirtualJoystick._globalJoystickIndex = 0;
  80085. return VirtualJoystick;
  80086. }());
  80087. BABYLON.VirtualJoystick = VirtualJoystick;
  80088. })(BABYLON || (BABYLON = {}));
  80089. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80090. var BABYLON;
  80091. (function (BABYLON) {
  80092. // We're mainly based on the logic defined into the FreeCamera code
  80093. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80094. __extends(VirtualJoysticksCamera, _super);
  80095. function VirtualJoysticksCamera(name, position, scene) {
  80096. var _this = _super.call(this, name, position, scene) || this;
  80097. _this.inputs.addVirtualJoystick();
  80098. return _this;
  80099. }
  80100. VirtualJoysticksCamera.prototype.getClassName = function () {
  80101. return "VirtualJoysticksCamera";
  80102. };
  80103. return VirtualJoysticksCamera;
  80104. }(BABYLON.FreeCamera));
  80105. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80106. })(BABYLON || (BABYLON = {}));
  80107. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80108. var BABYLON;
  80109. (function (BABYLON) {
  80110. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80111. function FreeCameraVirtualJoystickInput() {
  80112. }
  80113. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80114. return this._leftjoystick;
  80115. };
  80116. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80117. return this._rightjoystick;
  80118. };
  80119. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80120. if (this._leftjoystick) {
  80121. var camera = this.camera;
  80122. var speed = camera._computeLocalCameraSpeed() * 50;
  80123. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80124. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80125. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80126. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80127. if (!this._leftjoystick.pressed) {
  80128. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80129. }
  80130. if (!this._rightjoystick.pressed) {
  80131. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80132. }
  80133. }
  80134. };
  80135. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80136. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80137. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80138. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80139. this._leftjoystick.setJoystickSensibility(0.15);
  80140. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80141. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80142. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80143. this._rightjoystick.reverseUpDown = true;
  80144. this._rightjoystick.setJoystickSensibility(0.05);
  80145. this._rightjoystick.setJoystickColor("yellow");
  80146. };
  80147. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80148. this._leftjoystick.releaseCanvas();
  80149. this._rightjoystick.releaseCanvas();
  80150. };
  80151. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80152. return "FreeCameraVirtualJoystickInput";
  80153. };
  80154. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80155. return "virtualJoystick";
  80156. };
  80157. return FreeCameraVirtualJoystickInput;
  80158. }());
  80159. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80160. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80161. })(BABYLON || (BABYLON = {}));
  80162. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80163. var BABYLON;
  80164. (function (BABYLON) {
  80165. var SimplificationSettings = /** @class */ (function () {
  80166. function SimplificationSettings(quality, distance, optimizeMesh) {
  80167. this.quality = quality;
  80168. this.distance = distance;
  80169. this.optimizeMesh = optimizeMesh;
  80170. }
  80171. return SimplificationSettings;
  80172. }());
  80173. BABYLON.SimplificationSettings = SimplificationSettings;
  80174. var SimplificationQueue = /** @class */ (function () {
  80175. function SimplificationQueue() {
  80176. this.running = false;
  80177. this._simplificationArray = [];
  80178. }
  80179. SimplificationQueue.prototype.addTask = function (task) {
  80180. this._simplificationArray.push(task);
  80181. };
  80182. SimplificationQueue.prototype.executeNext = function () {
  80183. var task = this._simplificationArray.pop();
  80184. if (task) {
  80185. this.running = true;
  80186. this.runSimplification(task);
  80187. }
  80188. else {
  80189. this.running = false;
  80190. }
  80191. };
  80192. SimplificationQueue.prototype.runSimplification = function (task) {
  80193. var _this = this;
  80194. if (task.parallelProcessing) {
  80195. //parallel simplifier
  80196. task.settings.forEach(function (setting) {
  80197. var simplifier = _this.getSimplifier(task);
  80198. simplifier.simplify(setting, function (newMesh) {
  80199. task.mesh.addLODLevel(setting.distance, newMesh);
  80200. newMesh.isVisible = true;
  80201. //check if it is the last
  80202. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80203. //all done, run the success callback.
  80204. task.successCallback();
  80205. }
  80206. _this.executeNext();
  80207. });
  80208. });
  80209. }
  80210. else {
  80211. //single simplifier.
  80212. var simplifier = this.getSimplifier(task);
  80213. var runDecimation = function (setting, callback) {
  80214. simplifier.simplify(setting, function (newMesh) {
  80215. task.mesh.addLODLevel(setting.distance, newMesh);
  80216. newMesh.isVisible = true;
  80217. //run the next quality level
  80218. callback();
  80219. });
  80220. };
  80221. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80222. runDecimation(task.settings[loop.index], function () {
  80223. loop.executeNext();
  80224. });
  80225. }, function () {
  80226. //execution ended, run the success callback.
  80227. if (task.successCallback) {
  80228. task.successCallback();
  80229. }
  80230. _this.executeNext();
  80231. });
  80232. }
  80233. };
  80234. SimplificationQueue.prototype.getSimplifier = function (task) {
  80235. switch (task.simplificationType) {
  80236. case SimplificationType.QUADRATIC:
  80237. default:
  80238. return new QuadraticErrorSimplification(task.mesh);
  80239. }
  80240. };
  80241. return SimplificationQueue;
  80242. }());
  80243. BABYLON.SimplificationQueue = SimplificationQueue;
  80244. /**
  80245. * The implemented types of simplification.
  80246. * At the moment only Quadratic Error Decimation is implemented.
  80247. */
  80248. var SimplificationType;
  80249. (function (SimplificationType) {
  80250. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80251. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80252. var DecimationTriangle = /** @class */ (function () {
  80253. function DecimationTriangle(vertices) {
  80254. this.vertices = vertices;
  80255. this.error = new Array(4);
  80256. this.deleted = false;
  80257. this.isDirty = false;
  80258. this.deletePending = false;
  80259. this.borderFactor = 0;
  80260. }
  80261. return DecimationTriangle;
  80262. }());
  80263. BABYLON.DecimationTriangle = DecimationTriangle;
  80264. var DecimationVertex = /** @class */ (function () {
  80265. function DecimationVertex(position, id) {
  80266. this.position = position;
  80267. this.id = id;
  80268. this.isBorder = true;
  80269. this.q = new QuadraticMatrix();
  80270. this.triangleCount = 0;
  80271. this.triangleStart = 0;
  80272. this.originalOffsets = [];
  80273. }
  80274. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80275. this.position.copyFrom(newPosition);
  80276. };
  80277. return DecimationVertex;
  80278. }());
  80279. BABYLON.DecimationVertex = DecimationVertex;
  80280. var QuadraticMatrix = /** @class */ (function () {
  80281. function QuadraticMatrix(data) {
  80282. this.data = new Array(10);
  80283. for (var i = 0; i < 10; ++i) {
  80284. if (data && data[i]) {
  80285. this.data[i] = data[i];
  80286. }
  80287. else {
  80288. this.data[i] = 0;
  80289. }
  80290. }
  80291. }
  80292. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80293. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80294. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80295. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80296. return det;
  80297. };
  80298. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80299. for (var i = 0; i < 10; ++i) {
  80300. this.data[i] += matrix.data[i];
  80301. }
  80302. };
  80303. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80304. for (var i = 0; i < 10; ++i) {
  80305. this.data[i] += data[i];
  80306. }
  80307. };
  80308. QuadraticMatrix.prototype.add = function (matrix) {
  80309. var m = new QuadraticMatrix();
  80310. for (var i = 0; i < 10; ++i) {
  80311. m.data[i] = this.data[i] + matrix.data[i];
  80312. }
  80313. return m;
  80314. };
  80315. QuadraticMatrix.FromData = function (a, b, c, d) {
  80316. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80317. };
  80318. //returning an array to avoid garbage collection
  80319. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80320. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80321. };
  80322. return QuadraticMatrix;
  80323. }());
  80324. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80325. var Reference = /** @class */ (function () {
  80326. function Reference(vertexId, triangleId) {
  80327. this.vertexId = vertexId;
  80328. this.triangleId = triangleId;
  80329. }
  80330. return Reference;
  80331. }());
  80332. BABYLON.Reference = Reference;
  80333. /**
  80334. * An implementation of the Quadratic Error simplification algorithm.
  80335. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80336. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80337. * @author RaananW
  80338. */
  80339. var QuadraticErrorSimplification = /** @class */ (function () {
  80340. function QuadraticErrorSimplification(_mesh) {
  80341. this._mesh = _mesh;
  80342. this.syncIterations = 5000;
  80343. this.aggressiveness = 7;
  80344. this.decimationIterations = 100;
  80345. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80346. }
  80347. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80348. var _this = this;
  80349. this.initDecimatedMesh();
  80350. //iterating through the submeshes array, one after the other.
  80351. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80352. _this.initWithMesh(loop.index, function () {
  80353. _this.runDecimation(settings, loop.index, function () {
  80354. loop.executeNext();
  80355. });
  80356. }, settings.optimizeMesh);
  80357. }, function () {
  80358. setTimeout(function () {
  80359. successCallback(_this._reconstructedMesh);
  80360. }, 0);
  80361. });
  80362. };
  80363. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80364. var _this = this;
  80365. var targetCount = ~~(this.triangles.length * settings.quality);
  80366. var deletedTriangles = 0;
  80367. var triangleCount = this.triangles.length;
  80368. var iterationFunction = function (iteration, callback) {
  80369. setTimeout(function () {
  80370. if (iteration % 5 === 0) {
  80371. _this.updateMesh(iteration === 0);
  80372. }
  80373. for (var i = 0; i < _this.triangles.length; ++i) {
  80374. _this.triangles[i].isDirty = false;
  80375. }
  80376. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80377. var trianglesIterator = function (i) {
  80378. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80379. var t = _this.triangles[tIdx];
  80380. if (!t)
  80381. return;
  80382. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80383. return;
  80384. }
  80385. for (var j = 0; j < 3; ++j) {
  80386. if (t.error[j] < threshold) {
  80387. var deleted0 = [];
  80388. var deleted1 = [];
  80389. var v0 = t.vertices[j];
  80390. var v1 = t.vertices[(j + 1) % 3];
  80391. if (v0.isBorder || v1.isBorder)
  80392. continue;
  80393. var p = BABYLON.Vector3.Zero();
  80394. var n = BABYLON.Vector3.Zero();
  80395. var uv = BABYLON.Vector2.Zero();
  80396. var color = new BABYLON.Color4(0, 0, 0, 1);
  80397. _this.calculateError(v0, v1, p, n, uv, color);
  80398. var delTr = new Array();
  80399. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80400. continue;
  80401. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80402. continue;
  80403. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80404. continue;
  80405. var uniqueArray = new Array();
  80406. delTr.forEach(function (deletedT) {
  80407. if (uniqueArray.indexOf(deletedT) === -1) {
  80408. deletedT.deletePending = true;
  80409. uniqueArray.push(deletedT);
  80410. }
  80411. });
  80412. if (uniqueArray.length % 2 !== 0) {
  80413. continue;
  80414. }
  80415. v0.q = v1.q.add(v0.q);
  80416. v0.updatePosition(p);
  80417. var tStart = _this.references.length;
  80418. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80419. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80420. var tCount = _this.references.length - tStart;
  80421. if (tCount <= v0.triangleCount) {
  80422. if (tCount) {
  80423. for (var c = 0; c < tCount; c++) {
  80424. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80425. }
  80426. }
  80427. }
  80428. else {
  80429. v0.triangleStart = tStart;
  80430. }
  80431. v0.triangleCount = tCount;
  80432. break;
  80433. }
  80434. }
  80435. };
  80436. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80437. }, 0);
  80438. };
  80439. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80440. if (triangleCount - deletedTriangles <= targetCount)
  80441. loop.breakLoop();
  80442. else {
  80443. iterationFunction(loop.index, function () {
  80444. loop.executeNext();
  80445. });
  80446. }
  80447. }, function () {
  80448. setTimeout(function () {
  80449. //reconstruct this part of the mesh
  80450. _this.reconstructMesh(submeshIndex);
  80451. successCallback();
  80452. }, 0);
  80453. });
  80454. };
  80455. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80456. var _this = this;
  80457. this.vertices = [];
  80458. this.triangles = [];
  80459. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80460. var indices = this._mesh.getIndices();
  80461. var submesh = this._mesh.subMeshes[submeshIndex];
  80462. var findInVertices = function (positionToSearch) {
  80463. if (optimizeMesh) {
  80464. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80465. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80466. return _this.vertices[ii];
  80467. }
  80468. }
  80469. }
  80470. return null;
  80471. };
  80472. var vertexReferences = [];
  80473. var vertexInit = function (i) {
  80474. if (!positionData) {
  80475. return;
  80476. }
  80477. var offset = i + submesh.verticesStart;
  80478. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80479. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80480. vertex.originalOffsets.push(offset);
  80481. if (vertex.id === _this.vertices.length) {
  80482. _this.vertices.push(vertex);
  80483. }
  80484. vertexReferences.push(vertex.id);
  80485. };
  80486. //var totalVertices = mesh.getTotalVertices();
  80487. var totalVertices = submesh.verticesCount;
  80488. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80489. var indicesInit = function (i) {
  80490. if (!indices) {
  80491. return;
  80492. }
  80493. var offset = (submesh.indexStart / 3) + i;
  80494. var pos = (offset * 3);
  80495. var i0 = indices[pos + 0];
  80496. var i1 = indices[pos + 1];
  80497. var i2 = indices[pos + 2];
  80498. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80499. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80500. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80501. var triangle = new DecimationTriangle([v0, v1, v2]);
  80502. triangle.originalOffset = pos;
  80503. _this.triangles.push(triangle);
  80504. };
  80505. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80506. _this.init(callback);
  80507. });
  80508. });
  80509. };
  80510. QuadraticErrorSimplification.prototype.init = function (callback) {
  80511. var _this = this;
  80512. var triangleInit1 = function (i) {
  80513. var t = _this.triangles[i];
  80514. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80515. for (var j = 0; j < 3; j++) {
  80516. 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))));
  80517. }
  80518. };
  80519. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80520. var triangleInit2 = function (i) {
  80521. var t = _this.triangles[i];
  80522. for (var j = 0; j < 3; ++j) {
  80523. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80524. }
  80525. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80526. };
  80527. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80528. callback();
  80529. });
  80530. });
  80531. };
  80532. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80533. var newTriangles = [];
  80534. var i;
  80535. for (i = 0; i < this.vertices.length; ++i) {
  80536. this.vertices[i].triangleCount = 0;
  80537. }
  80538. var t;
  80539. var j;
  80540. for (i = 0; i < this.triangles.length; ++i) {
  80541. if (!this.triangles[i].deleted) {
  80542. t = this.triangles[i];
  80543. for (j = 0; j < 3; ++j) {
  80544. t.vertices[j].triangleCount = 1;
  80545. }
  80546. newTriangles.push(t);
  80547. }
  80548. }
  80549. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80550. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80551. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80552. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80553. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80554. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80555. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80556. var vertexCount = 0;
  80557. for (i = 0; i < this.vertices.length; ++i) {
  80558. var vertex = this.vertices[i];
  80559. vertex.id = vertexCount;
  80560. if (vertex.triangleCount) {
  80561. vertex.originalOffsets.forEach(function (originalOffset) {
  80562. if (!normalData) {
  80563. return;
  80564. }
  80565. newPositionData.push(vertex.position.x);
  80566. newPositionData.push(vertex.position.y);
  80567. newPositionData.push(vertex.position.z);
  80568. newNormalData.push(normalData[originalOffset * 3]);
  80569. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80570. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80571. if (uvs && uvs.length) {
  80572. newUVsData.push(uvs[(originalOffset * 2)]);
  80573. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80574. }
  80575. else if (colorsData && colorsData.length) {
  80576. newColorsData.push(colorsData[(originalOffset * 4)]);
  80577. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80578. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80579. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80580. }
  80581. ++vertexCount;
  80582. });
  80583. }
  80584. }
  80585. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80586. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80587. var submeshesArray = this._reconstructedMesh.subMeshes;
  80588. this._reconstructedMesh.subMeshes = [];
  80589. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80590. var originalIndices = this._mesh.getIndices();
  80591. for (i = 0; i < newTriangles.length; ++i) {
  80592. t = newTriangles[i]; //now get the new referencing point for each vertex
  80593. [0, 1, 2].forEach(function (idx) {
  80594. var id = originalIndices[t.originalOffset + idx];
  80595. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80596. if (offset < 0)
  80597. offset = 0;
  80598. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80599. });
  80600. }
  80601. //overwriting the old vertex buffers and indices.
  80602. this._reconstructedMesh.setIndices(newIndicesArray);
  80603. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80604. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80605. if (newUVsData.length > 0)
  80606. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80607. if (newColorsData.length > 0)
  80608. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80609. //create submesh
  80610. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80611. if (submeshIndex > 0) {
  80612. this._reconstructedMesh.subMeshes = [];
  80613. submeshesArray.forEach(function (submesh) {
  80614. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80615. });
  80616. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80617. }
  80618. };
  80619. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80620. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80621. this._reconstructedMesh.material = this._mesh.material;
  80622. this._reconstructedMesh.parent = this._mesh.parent;
  80623. this._reconstructedMesh.isVisible = false;
  80624. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80625. };
  80626. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80627. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80628. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80629. if (t.deleted)
  80630. continue;
  80631. var s = this.references[vertex1.triangleStart + i].vertexId;
  80632. var v1 = t.vertices[(s + 1) % 3];
  80633. var v2 = t.vertices[(s + 2) % 3];
  80634. if ((v1 === vertex2 || v2 === vertex2)) {
  80635. deletedArray[i] = true;
  80636. delTr.push(t);
  80637. continue;
  80638. }
  80639. var d1 = v1.position.subtract(point);
  80640. d1 = d1.normalize();
  80641. var d2 = v2.position.subtract(point);
  80642. d2 = d2.normalize();
  80643. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80644. return true;
  80645. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80646. deletedArray[i] = false;
  80647. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80648. return true;
  80649. }
  80650. return false;
  80651. };
  80652. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80653. var newDeleted = deletedTriangles;
  80654. for (var i = 0; i < vertex.triangleCount; ++i) {
  80655. var ref = this.references[vertex.triangleStart + i];
  80656. var t = this.triangles[ref.triangleId];
  80657. if (t.deleted)
  80658. continue;
  80659. if (deletedArray[i] && t.deletePending) {
  80660. t.deleted = true;
  80661. newDeleted++;
  80662. continue;
  80663. }
  80664. t.vertices[ref.vertexId] = origVertex;
  80665. t.isDirty = true;
  80666. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80667. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80668. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80669. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80670. this.references.push(ref);
  80671. }
  80672. return newDeleted;
  80673. };
  80674. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80675. for (var i = 0; i < this.vertices.length; ++i) {
  80676. var vCount = [];
  80677. var vId = [];
  80678. var v = this.vertices[i];
  80679. var j;
  80680. for (j = 0; j < v.triangleCount; ++j) {
  80681. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80682. for (var ii = 0; ii < 3; ii++) {
  80683. var ofs = 0;
  80684. var vv = triangle.vertices[ii];
  80685. while (ofs < vCount.length) {
  80686. if (vId[ofs] === vv.id)
  80687. break;
  80688. ++ofs;
  80689. }
  80690. if (ofs === vCount.length) {
  80691. vCount.push(1);
  80692. vId.push(vv.id);
  80693. }
  80694. else {
  80695. vCount[ofs]++;
  80696. }
  80697. }
  80698. }
  80699. for (j = 0; j < vCount.length; ++j) {
  80700. if (vCount[j] === 1) {
  80701. this.vertices[vId[j]].isBorder = true;
  80702. }
  80703. else {
  80704. this.vertices[vId[j]].isBorder = false;
  80705. }
  80706. }
  80707. }
  80708. };
  80709. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80710. if (identifyBorders === void 0) { identifyBorders = false; }
  80711. var i;
  80712. if (!identifyBorders) {
  80713. var newTrianglesVector = [];
  80714. for (i = 0; i < this.triangles.length; ++i) {
  80715. if (!this.triangles[i].deleted) {
  80716. newTrianglesVector.push(this.triangles[i]);
  80717. }
  80718. }
  80719. this.triangles = newTrianglesVector;
  80720. }
  80721. for (i = 0; i < this.vertices.length; ++i) {
  80722. this.vertices[i].triangleCount = 0;
  80723. this.vertices[i].triangleStart = 0;
  80724. }
  80725. var t;
  80726. var j;
  80727. var v;
  80728. for (i = 0; i < this.triangles.length; ++i) {
  80729. t = this.triangles[i];
  80730. for (j = 0; j < 3; ++j) {
  80731. v = t.vertices[j];
  80732. v.triangleCount++;
  80733. }
  80734. }
  80735. var tStart = 0;
  80736. for (i = 0; i < this.vertices.length; ++i) {
  80737. this.vertices[i].triangleStart = tStart;
  80738. tStart += this.vertices[i].triangleCount;
  80739. this.vertices[i].triangleCount = 0;
  80740. }
  80741. var newReferences = new Array(this.triangles.length * 3);
  80742. for (i = 0; i < this.triangles.length; ++i) {
  80743. t = this.triangles[i];
  80744. for (j = 0; j < 3; ++j) {
  80745. v = t.vertices[j];
  80746. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80747. v.triangleCount++;
  80748. }
  80749. }
  80750. this.references = newReferences;
  80751. if (identifyBorders) {
  80752. this.identifyBorder();
  80753. }
  80754. };
  80755. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80756. var x = point.x;
  80757. var y = point.y;
  80758. var z = point.z;
  80759. 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
  80760. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80761. };
  80762. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80763. var q = vertex1.q.add(vertex2.q);
  80764. var border = vertex1.isBorder && vertex2.isBorder;
  80765. var error = 0;
  80766. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80767. if (qDet !== 0 && !border) {
  80768. if (!pointResult) {
  80769. pointResult = BABYLON.Vector3.Zero();
  80770. }
  80771. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80772. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80773. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80774. error = this.vertexError(q, pointResult);
  80775. }
  80776. else {
  80777. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80778. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80779. var error1 = this.vertexError(q, vertex1.position);
  80780. var error2 = this.vertexError(q, vertex2.position);
  80781. var error3 = this.vertexError(q, p3);
  80782. error = Math.min(error1, error2, error3);
  80783. if (error === error1) {
  80784. if (pointResult) {
  80785. pointResult.copyFrom(vertex1.position);
  80786. }
  80787. }
  80788. else if (error === error2) {
  80789. if (pointResult) {
  80790. pointResult.copyFrom(vertex2.position);
  80791. }
  80792. }
  80793. else {
  80794. if (pointResult) {
  80795. pointResult.copyFrom(p3);
  80796. }
  80797. }
  80798. }
  80799. return error;
  80800. };
  80801. return QuadraticErrorSimplification;
  80802. }());
  80803. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80804. })(BABYLON || (BABYLON = {}));
  80805. //# sourceMappingURL=babylon.meshSimplification.js.map
  80806. var BABYLON;
  80807. (function (BABYLON) {
  80808. var MeshLODLevel = /** @class */ (function () {
  80809. function MeshLODLevel(distance, mesh) {
  80810. this.distance = distance;
  80811. this.mesh = mesh;
  80812. }
  80813. return MeshLODLevel;
  80814. }());
  80815. BABYLON.MeshLODLevel = MeshLODLevel;
  80816. })(BABYLON || (BABYLON = {}));
  80817. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80818. var BABYLON;
  80819. (function (BABYLON) {
  80820. /**
  80821. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80822. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80823. */
  80824. var SceneOptimization = /** @class */ (function () {
  80825. /**
  80826. * Creates the SceneOptimization object
  80827. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80828. * @param desc defines the description associated with the optimization
  80829. */
  80830. function SceneOptimization(
  80831. /**
  80832. * Defines the priority of this optimization (0 by default which means first in the list)
  80833. */
  80834. priority) {
  80835. if (priority === void 0) { priority = 0; }
  80836. this.priority = priority;
  80837. }
  80838. /**
  80839. * Gets a string describing the action executed by the current optimization
  80840. * @returns description string
  80841. */
  80842. SceneOptimization.prototype.getDescription = function () {
  80843. return "";
  80844. };
  80845. /**
  80846. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80847. * @param scene defines the current scene where to apply this optimization
  80848. * @param optimizer defines the current optimizer
  80849. * @returns true if everything that can be done was applied
  80850. */
  80851. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80852. return true;
  80853. };
  80854. ;
  80855. return SceneOptimization;
  80856. }());
  80857. BABYLON.SceneOptimization = SceneOptimization;
  80858. /**
  80859. * Defines an optimization used to reduce the size of render target textures
  80860. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80861. */
  80862. var TextureOptimization = /** @class */ (function (_super) {
  80863. __extends(TextureOptimization, _super);
  80864. /**
  80865. * Creates the TextureOptimization object
  80866. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80867. * @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
  80868. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80869. */
  80870. function TextureOptimization(
  80871. /**
  80872. * Defines the priority of this optimization (0 by default which means first in the list)
  80873. */
  80874. priority,
  80875. /**
  80876. * 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
  80877. */
  80878. maximumSize,
  80879. /**
  80880. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80881. */
  80882. step) {
  80883. if (priority === void 0) { priority = 0; }
  80884. if (maximumSize === void 0) { maximumSize = 1024; }
  80885. if (step === void 0) { step = 0.5; }
  80886. var _this = _super.call(this, priority) || this;
  80887. _this.priority = priority;
  80888. _this.maximumSize = maximumSize;
  80889. _this.step = step;
  80890. return _this;
  80891. }
  80892. /**
  80893. * Gets a string describing the action executed by the current optimization
  80894. * @returns description string
  80895. */
  80896. TextureOptimization.prototype.getDescription = function () {
  80897. return "Reducing render target texture size to " + this.maximumSize;
  80898. };
  80899. /**
  80900. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80901. * @param scene defines the current scene where to apply this optimization
  80902. * @param optimizer defines the current optimizer
  80903. * @returns true if everything that can be done was applied
  80904. */
  80905. TextureOptimization.prototype.apply = function (scene, optimizer) {
  80906. var allDone = true;
  80907. for (var index = 0; index < scene.textures.length; index++) {
  80908. var texture = scene.textures[index];
  80909. if (!texture.canRescale || texture.getContext) {
  80910. continue;
  80911. }
  80912. var currentSize = texture.getSize();
  80913. var maxDimension = Math.max(currentSize.width, currentSize.height);
  80914. if (maxDimension > this.maximumSize) {
  80915. texture.scale(this.step);
  80916. allDone = false;
  80917. }
  80918. }
  80919. return allDone;
  80920. };
  80921. return TextureOptimization;
  80922. }(SceneOptimization));
  80923. BABYLON.TextureOptimization = TextureOptimization;
  80924. /**
  80925. * Defines an optimization used to increase or decrease the rendering resolution
  80926. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80927. */
  80928. var HardwareScalingOptimization = /** @class */ (function (_super) {
  80929. __extends(HardwareScalingOptimization, _super);
  80930. /**
  80931. * Creates the HardwareScalingOptimization object
  80932. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80933. * @param maximumScale defines the maximum scale to use (2 by default)
  80934. * @param step defines the step to use between two passes (0.5 by default)
  80935. */
  80936. function HardwareScalingOptimization(
  80937. /**
  80938. * Defines the priority of this optimization (0 by default which means first in the list)
  80939. */
  80940. priority,
  80941. /**
  80942. * Defines the maximum scale to use (2 by default)
  80943. */
  80944. maximumScale,
  80945. /**
  80946. * Defines the step to use between two passes (0.5 by default)
  80947. */
  80948. step) {
  80949. if (priority === void 0) { priority = 0; }
  80950. if (maximumScale === void 0) { maximumScale = 2; }
  80951. if (step === void 0) { step = 0.25; }
  80952. var _this = _super.call(this, priority) || this;
  80953. _this.priority = priority;
  80954. _this.maximumScale = maximumScale;
  80955. _this.step = step;
  80956. _this._currentScale = -1;
  80957. _this._directionOffset = 1;
  80958. return _this;
  80959. }
  80960. /**
  80961. * Gets a string describing the action executed by the current optimization
  80962. * @return description string
  80963. */
  80964. HardwareScalingOptimization.prototype.getDescription = function () {
  80965. return "Setting hardware scaling level to " + this._currentScale;
  80966. };
  80967. /**
  80968. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80969. * @param scene defines the current scene where to apply this optimization
  80970. * @param optimizer defines the current optimizer
  80971. * @returns true if everything that can be done was applied
  80972. */
  80973. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  80974. if (this._currentScale === -1) {
  80975. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  80976. if (this._currentScale > this.maximumScale) {
  80977. this._directionOffset = -1;
  80978. }
  80979. }
  80980. this._currentScale += this._directionOffset * this.step;
  80981. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  80982. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  80983. };
  80984. ;
  80985. return HardwareScalingOptimization;
  80986. }(SceneOptimization));
  80987. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  80988. /**
  80989. * Defines an optimization used to remove shadows
  80990. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80991. */
  80992. var ShadowsOptimization = /** @class */ (function (_super) {
  80993. __extends(ShadowsOptimization, _super);
  80994. function ShadowsOptimization() {
  80995. return _super !== null && _super.apply(this, arguments) || this;
  80996. }
  80997. /**
  80998. * Gets a string describing the action executed by the current optimization
  80999. * @return description string
  81000. */
  81001. ShadowsOptimization.prototype.getDescription = function () {
  81002. return "Turning shadows on/off";
  81003. };
  81004. /**
  81005. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81006. * @param scene defines the current scene where to apply this optimization
  81007. * @param optimizer defines the current optimizer
  81008. * @returns true if everything that can be done was applied
  81009. */
  81010. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81011. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81012. return true;
  81013. };
  81014. ;
  81015. return ShadowsOptimization;
  81016. }(SceneOptimization));
  81017. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81018. /**
  81019. * Defines an optimization used to turn post-processes off
  81020. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81021. */
  81022. var PostProcessesOptimization = /** @class */ (function (_super) {
  81023. __extends(PostProcessesOptimization, _super);
  81024. function PostProcessesOptimization() {
  81025. return _super !== null && _super.apply(this, arguments) || this;
  81026. }
  81027. /**
  81028. * Gets a string describing the action executed by the current optimization
  81029. * @return description string
  81030. */
  81031. PostProcessesOptimization.prototype.getDescription = function () {
  81032. return "Turning post-processes on/off";
  81033. };
  81034. /**
  81035. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81036. * @param scene defines the current scene where to apply this optimization
  81037. * @param optimizer defines the current optimizer
  81038. * @returns true if everything that can be done was applied
  81039. */
  81040. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81041. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81042. return true;
  81043. };
  81044. ;
  81045. return PostProcessesOptimization;
  81046. }(SceneOptimization));
  81047. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81048. /**
  81049. * Defines an optimization used to turn lens flares off
  81050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81051. */
  81052. var LensFlaresOptimization = /** @class */ (function (_super) {
  81053. __extends(LensFlaresOptimization, _super);
  81054. function LensFlaresOptimization() {
  81055. return _super !== null && _super.apply(this, arguments) || this;
  81056. }
  81057. /**
  81058. * Gets a string describing the action executed by the current optimization
  81059. * @return description string
  81060. */
  81061. LensFlaresOptimization.prototype.getDescription = function () {
  81062. return "Turning lens flares on/off";
  81063. };
  81064. /**
  81065. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81066. * @param scene defines the current scene where to apply this optimization
  81067. * @param optimizer defines the current optimizer
  81068. * @returns true if everything that can be done was applied
  81069. */
  81070. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81071. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81072. return true;
  81073. };
  81074. ;
  81075. return LensFlaresOptimization;
  81076. }(SceneOptimization));
  81077. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81078. /**
  81079. * Defines an optimization based on user defined callback.
  81080. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81081. */
  81082. var CustomOptimization = /** @class */ (function (_super) {
  81083. __extends(CustomOptimization, _super);
  81084. function CustomOptimization() {
  81085. return _super !== null && _super.apply(this, arguments) || this;
  81086. }
  81087. /**
  81088. * Gets a string describing the action executed by the current optimization
  81089. * @returns description string
  81090. */
  81091. CustomOptimization.prototype.getDescription = function () {
  81092. if (this.onGetDescription) {
  81093. return this.onGetDescription();
  81094. }
  81095. return "Running user defined callback";
  81096. };
  81097. /**
  81098. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81099. * @param scene defines the current scene where to apply this optimization
  81100. * @param optimizer defines the current optimizer
  81101. * @returns true if everything that can be done was applied
  81102. */
  81103. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81104. if (this.onApply) {
  81105. return this.onApply(scene, optimizer);
  81106. }
  81107. return true;
  81108. };
  81109. ;
  81110. return CustomOptimization;
  81111. }(SceneOptimization));
  81112. BABYLON.CustomOptimization = CustomOptimization;
  81113. /**
  81114. * Defines an optimization used to turn particles off
  81115. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81116. */
  81117. var ParticlesOptimization = /** @class */ (function (_super) {
  81118. __extends(ParticlesOptimization, _super);
  81119. function ParticlesOptimization() {
  81120. return _super !== null && _super.apply(this, arguments) || this;
  81121. }
  81122. /**
  81123. * Gets a string describing the action executed by the current optimization
  81124. * @return description string
  81125. */
  81126. ParticlesOptimization.prototype.getDescription = function () {
  81127. return "Turning particles on/off";
  81128. };
  81129. /**
  81130. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81131. * @param scene defines the current scene where to apply this optimization
  81132. * @param optimizer defines the current optimizer
  81133. * @returns true if everything that can be done was applied
  81134. */
  81135. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81136. scene.particlesEnabled = optimizer.isInImprovementMode;
  81137. return true;
  81138. };
  81139. ;
  81140. return ParticlesOptimization;
  81141. }(SceneOptimization));
  81142. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81143. /**
  81144. * Defines an optimization used to turn render targets off
  81145. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81146. */
  81147. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81148. __extends(RenderTargetsOptimization, _super);
  81149. function RenderTargetsOptimization() {
  81150. return _super !== null && _super.apply(this, arguments) || this;
  81151. }
  81152. /**
  81153. * Gets a string describing the action executed by the current optimization
  81154. * @return description string
  81155. */
  81156. RenderTargetsOptimization.prototype.getDescription = function () {
  81157. return "Turning render targets off";
  81158. };
  81159. /**
  81160. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81161. * @param scene defines the current scene where to apply this optimization
  81162. * @param optimizer defines the current optimizer
  81163. * @returns true if everything that can be done was applied
  81164. */
  81165. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81166. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81167. return true;
  81168. };
  81169. ;
  81170. return RenderTargetsOptimization;
  81171. }(SceneOptimization));
  81172. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81173. /**
  81174. * Defines an optimization used to merge meshes with compatible materials
  81175. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81176. */
  81177. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81178. __extends(MergeMeshesOptimization, _super);
  81179. function MergeMeshesOptimization() {
  81180. var _this = _super !== null && _super.apply(this, arguments) || this;
  81181. _this._canBeMerged = function (abstractMesh) {
  81182. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81183. return false;
  81184. }
  81185. var mesh = abstractMesh;
  81186. if (!mesh.isVisible || !mesh.isEnabled()) {
  81187. return false;
  81188. }
  81189. if (mesh.instances.length > 0) {
  81190. return false;
  81191. }
  81192. if (mesh.skeleton || mesh.hasLODLevels) {
  81193. return false;
  81194. }
  81195. if (mesh.parent) {
  81196. return false;
  81197. }
  81198. return true;
  81199. };
  81200. return _this;
  81201. }
  81202. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81203. /**
  81204. * Gets or sets a boolean which defines if optimization octree has to be updated
  81205. */
  81206. get: function () {
  81207. return MergeMeshesOptimization._UpdateSelectionTree;
  81208. },
  81209. /**
  81210. * Gets or sets a boolean which defines if optimization octree has to be updated
  81211. */
  81212. set: function (value) {
  81213. MergeMeshesOptimization._UpdateSelectionTree = value;
  81214. },
  81215. enumerable: true,
  81216. configurable: true
  81217. });
  81218. /**
  81219. * Gets a string describing the action executed by the current optimization
  81220. * @return description string
  81221. */
  81222. MergeMeshesOptimization.prototype.getDescription = function () {
  81223. return "Merging similar meshes together";
  81224. };
  81225. /**
  81226. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81227. * @param scene defines the current scene where to apply this optimization
  81228. * @param optimizer defines the current optimizer
  81229. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81230. * @returns true if everything that can be done was applied
  81231. */
  81232. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81233. var globalPool = scene.meshes.slice(0);
  81234. var globalLength = globalPool.length;
  81235. for (var index = 0; index < globalLength; index++) {
  81236. var currentPool = new Array();
  81237. var current = globalPool[index];
  81238. // Checks
  81239. if (!this._canBeMerged(current)) {
  81240. continue;
  81241. }
  81242. currentPool.push(current);
  81243. // Find compatible meshes
  81244. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81245. var otherMesh = globalPool[subIndex];
  81246. if (!this._canBeMerged(otherMesh)) {
  81247. continue;
  81248. }
  81249. if (otherMesh.material !== current.material) {
  81250. continue;
  81251. }
  81252. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81253. continue;
  81254. }
  81255. currentPool.push(otherMesh);
  81256. globalLength--;
  81257. globalPool.splice(subIndex, 1);
  81258. subIndex--;
  81259. }
  81260. if (currentPool.length < 2) {
  81261. continue;
  81262. }
  81263. // Merge meshes
  81264. BABYLON.Mesh.MergeMeshes(currentPool);
  81265. }
  81266. if (updateSelectionTree != undefined) {
  81267. if (updateSelectionTree) {
  81268. scene.createOrUpdateSelectionOctree();
  81269. }
  81270. }
  81271. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81272. scene.createOrUpdateSelectionOctree();
  81273. }
  81274. return true;
  81275. };
  81276. ;
  81277. MergeMeshesOptimization._UpdateSelectionTree = false;
  81278. return MergeMeshesOptimization;
  81279. }(SceneOptimization));
  81280. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81281. /**
  81282. * Defines a list of options used by SceneOptimizer
  81283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81284. */
  81285. var SceneOptimizerOptions = /** @class */ (function () {
  81286. /**
  81287. * Creates a new list of options used by SceneOptimizer
  81288. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81289. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81290. */
  81291. function SceneOptimizerOptions(
  81292. /**
  81293. * Defines the target frame rate to reach (60 by default)
  81294. */
  81295. targetFrameRate,
  81296. /**
  81297. * Defines the interval between two checkes (2000ms by default)
  81298. */
  81299. trackerDuration) {
  81300. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81301. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81302. this.targetFrameRate = targetFrameRate;
  81303. this.trackerDuration = trackerDuration;
  81304. /**
  81305. * Gets the list of optimizations to apply
  81306. */
  81307. this.optimizations = new Array();
  81308. }
  81309. /**
  81310. * Add a new optimization
  81311. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81312. * @returns the current SceneOptimizerOptions
  81313. */
  81314. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81315. this.optimizations.push(optimization);
  81316. return this;
  81317. };
  81318. /**
  81319. * Add a new custom optimization
  81320. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81321. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81322. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81323. * @returns the current SceneOptimizerOptions
  81324. */
  81325. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81326. if (priority === void 0) { priority = 0; }
  81327. var optimization = new CustomOptimization(priority);
  81328. optimization.onApply = onApply;
  81329. optimization.onGetDescription = onGetDescription;
  81330. this.optimizations.push(optimization);
  81331. return this;
  81332. };
  81333. /**
  81334. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81335. * @param targetFrameRate defines the target frame rate (60 by default)
  81336. * @returns a SceneOptimizerOptions object
  81337. */
  81338. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81339. var result = new SceneOptimizerOptions(targetFrameRate);
  81340. var priority = 0;
  81341. result.addOptimization(new MergeMeshesOptimization(priority));
  81342. result.addOptimization(new ShadowsOptimization(priority));
  81343. result.addOptimization(new LensFlaresOptimization(priority));
  81344. // Next priority
  81345. priority++;
  81346. result.addOptimization(new PostProcessesOptimization(priority));
  81347. result.addOptimization(new ParticlesOptimization(priority));
  81348. // Next priority
  81349. priority++;
  81350. result.addOptimization(new TextureOptimization(priority, 1024));
  81351. return result;
  81352. };
  81353. /**
  81354. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81355. * @param targetFrameRate defines the target frame rate (60 by default)
  81356. * @returns a SceneOptimizerOptions object
  81357. */
  81358. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81359. var result = new SceneOptimizerOptions(targetFrameRate);
  81360. var priority = 0;
  81361. result.addOptimization(new MergeMeshesOptimization(priority));
  81362. result.addOptimization(new ShadowsOptimization(priority));
  81363. result.addOptimization(new LensFlaresOptimization(priority));
  81364. // Next priority
  81365. priority++;
  81366. result.addOptimization(new PostProcessesOptimization(priority));
  81367. result.addOptimization(new ParticlesOptimization(priority));
  81368. // Next priority
  81369. priority++;
  81370. result.addOptimization(new TextureOptimization(priority, 512));
  81371. // Next priority
  81372. priority++;
  81373. result.addOptimization(new RenderTargetsOptimization(priority));
  81374. // Next priority
  81375. priority++;
  81376. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81377. return result;
  81378. };
  81379. /**
  81380. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81381. * @param targetFrameRate defines the target frame rate (60 by default)
  81382. * @returns a SceneOptimizerOptions object
  81383. */
  81384. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81385. var result = new SceneOptimizerOptions(targetFrameRate);
  81386. var priority = 0;
  81387. result.addOptimization(new MergeMeshesOptimization(priority));
  81388. result.addOptimization(new ShadowsOptimization(priority));
  81389. result.addOptimization(new LensFlaresOptimization(priority));
  81390. // Next priority
  81391. priority++;
  81392. result.addOptimization(new PostProcessesOptimization(priority));
  81393. result.addOptimization(new ParticlesOptimization(priority));
  81394. // Next priority
  81395. priority++;
  81396. result.addOptimization(new TextureOptimization(priority, 256));
  81397. // Next priority
  81398. priority++;
  81399. result.addOptimization(new RenderTargetsOptimization(priority));
  81400. // Next priority
  81401. priority++;
  81402. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81403. return result;
  81404. };
  81405. return SceneOptimizerOptions;
  81406. }());
  81407. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81408. /**
  81409. * Class used to run optimizations in order to reach a target frame rate
  81410. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81411. */
  81412. var SceneOptimizer = /** @class */ (function () {
  81413. /**
  81414. * Creates a new SceneOptimizer
  81415. * @param scene defines the scene to work on
  81416. * @param options defines the options to use with the SceneOptimizer
  81417. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81418. * @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)
  81419. */
  81420. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81421. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81422. if (improvementMode === void 0) { improvementMode = false; }
  81423. var _this = this;
  81424. this._isRunning = false;
  81425. this._currentPriorityLevel = 0;
  81426. this._targetFrameRate = 60;
  81427. this._trackerDuration = 2000;
  81428. this._currentFrameRate = 0;
  81429. this._improvementMode = false;
  81430. /**
  81431. * Defines an observable called when the optimizer reaches the target frame rate
  81432. */
  81433. this.onSuccessObservable = new BABYLON.Observable();
  81434. /**
  81435. * Defines an observable called when the optimizer enables an optimization
  81436. */
  81437. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81438. /**
  81439. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81440. */
  81441. this.onFailureObservable = new BABYLON.Observable();
  81442. if (!options) {
  81443. this._options = new SceneOptimizerOptions();
  81444. }
  81445. else {
  81446. this._options = options;
  81447. }
  81448. if (this._options.targetFrameRate) {
  81449. this._targetFrameRate = this._options.targetFrameRate;
  81450. }
  81451. if (this._options.trackerDuration) {
  81452. this._trackerDuration = this._options.trackerDuration;
  81453. }
  81454. if (autoGeneratePriorities) {
  81455. var priority = 0;
  81456. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81457. var optim = _a[_i];
  81458. optim.priority = priority++;
  81459. }
  81460. }
  81461. this._improvementMode = improvementMode;
  81462. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81463. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81464. _this._sceneDisposeObserver = null;
  81465. _this.dispose();
  81466. });
  81467. }
  81468. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81469. /**
  81470. * Gets a boolean indicating if the optimizer is in improvement mode
  81471. */
  81472. get: function () {
  81473. return this._improvementMode;
  81474. },
  81475. enumerable: true,
  81476. configurable: true
  81477. });
  81478. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81479. /**
  81480. * Gets the current priority level (0 at start)
  81481. */
  81482. get: function () {
  81483. return this._currentPriorityLevel;
  81484. },
  81485. enumerable: true,
  81486. configurable: true
  81487. });
  81488. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81489. /**
  81490. * Gets the current frame rate checked by the SceneOptimizer
  81491. */
  81492. get: function () {
  81493. return this._currentFrameRate;
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81499. /**
  81500. * Gets or sets the current target frame rate (60 by default)
  81501. */
  81502. get: function () {
  81503. return this._targetFrameRate;
  81504. },
  81505. /**
  81506. * Gets or sets the current target frame rate (60 by default)
  81507. */
  81508. set: function (value) {
  81509. this._targetFrameRate = value;
  81510. },
  81511. enumerable: true,
  81512. configurable: true
  81513. });
  81514. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81515. /**
  81516. * Gets or sets the current interval between two checks (every 2000ms by default)
  81517. */
  81518. get: function () {
  81519. return this._trackerDuration;
  81520. },
  81521. /**
  81522. * Gets or sets the current interval between two checks (every 2000ms by default)
  81523. */
  81524. set: function (value) {
  81525. this._trackerDuration = value;
  81526. },
  81527. enumerable: true,
  81528. configurable: true
  81529. });
  81530. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81531. /**
  81532. * Gets the list of active optimizations
  81533. */
  81534. get: function () {
  81535. return this._options.optimizations;
  81536. },
  81537. enumerable: true,
  81538. configurable: true
  81539. });
  81540. /**
  81541. * Stops the current optimizer
  81542. */
  81543. SceneOptimizer.prototype.stop = function () {
  81544. this._isRunning = false;
  81545. };
  81546. /**
  81547. * Reset the optimizer to initial step (current priority level = 0)
  81548. */
  81549. SceneOptimizer.prototype.reset = function () {
  81550. this._currentPriorityLevel = 0;
  81551. };
  81552. /**
  81553. * Start the optimizer. By default it will try to reach a specific framerate
  81554. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81555. */
  81556. SceneOptimizer.prototype.start = function () {
  81557. var _this = this;
  81558. if (this._isRunning) {
  81559. return;
  81560. }
  81561. this._isRunning = true;
  81562. // Let's wait for the scene to be ready before running our check
  81563. this._scene.executeWhenReady(function () {
  81564. setTimeout(function () {
  81565. _this._checkCurrentState();
  81566. }, _this._trackerDuration);
  81567. });
  81568. };
  81569. SceneOptimizer.prototype._checkCurrentState = function () {
  81570. var _this = this;
  81571. if (!this._isRunning) {
  81572. return;
  81573. }
  81574. var scene = this._scene;
  81575. var options = this._options;
  81576. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81577. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81578. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81579. this._isRunning = false;
  81580. this.onSuccessObservable.notifyObservers(this);
  81581. return;
  81582. }
  81583. // Apply current level of optimizations
  81584. var allDone = true;
  81585. var noOptimizationApplied = true;
  81586. for (var index = 0; index < options.optimizations.length; index++) {
  81587. var optimization = options.optimizations[index];
  81588. if (optimization.priority === this._currentPriorityLevel) {
  81589. noOptimizationApplied = false;
  81590. allDone = allDone && optimization.apply(scene, this);
  81591. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81592. }
  81593. }
  81594. // If no optimization was applied, this is a failure :(
  81595. if (noOptimizationApplied) {
  81596. this._isRunning = false;
  81597. this.onFailureObservable.notifyObservers(this);
  81598. return;
  81599. }
  81600. // If all optimizations were done, move to next level
  81601. if (allDone) {
  81602. this._currentPriorityLevel++;
  81603. }
  81604. // Let's the system running for a specific amount of time before checking FPS
  81605. scene.executeWhenReady(function () {
  81606. setTimeout(function () {
  81607. _this._checkCurrentState();
  81608. }, _this._trackerDuration);
  81609. });
  81610. };
  81611. /**
  81612. * Release all resources
  81613. */
  81614. SceneOptimizer.prototype.dispose = function () {
  81615. this.stop();
  81616. this.onSuccessObservable.clear();
  81617. this.onFailureObservable.clear();
  81618. this.onNewOptimizationAppliedObservable.clear();
  81619. if (this._sceneDisposeObserver) {
  81620. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81621. }
  81622. };
  81623. /**
  81624. * Helper function to create a SceneOptimizer with one single line of code
  81625. * @param scene defines the scene to work on
  81626. * @param options defines the options to use with the SceneOptimizer
  81627. * @param onSuccess defines a callback to call on success
  81628. * @param onFailure defines a callback to call on failure
  81629. * @returns the new SceneOptimizer object
  81630. */
  81631. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81632. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81633. if (onSuccess) {
  81634. optimizer.onSuccessObservable.add(function () {
  81635. onSuccess();
  81636. });
  81637. }
  81638. if (onFailure) {
  81639. optimizer.onFailureObservable.add(function () {
  81640. onFailure();
  81641. });
  81642. }
  81643. optimizer.start();
  81644. return optimizer;
  81645. };
  81646. return SceneOptimizer;
  81647. }());
  81648. BABYLON.SceneOptimizer = SceneOptimizer;
  81649. })(BABYLON || (BABYLON = {}));
  81650. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81651. var BABYLON;
  81652. (function (BABYLON) {
  81653. var OutlineRenderer = /** @class */ (function () {
  81654. function OutlineRenderer(scene) {
  81655. this.zOffset = 1;
  81656. this._scene = scene;
  81657. }
  81658. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81659. var _this = this;
  81660. if (useOverlay === void 0) { useOverlay = false; }
  81661. var scene = this._scene;
  81662. var engine = this._scene.getEngine();
  81663. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81664. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81665. return;
  81666. }
  81667. var mesh = subMesh.getRenderingMesh();
  81668. var material = subMesh.getMaterial();
  81669. if (!material || !scene.activeCamera) {
  81670. return;
  81671. }
  81672. engine.enableEffect(this._effect);
  81673. // Logarithmic depth
  81674. if (material.useLogarithmicDepth) {
  81675. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81676. }
  81677. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81678. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81679. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81680. // Bones
  81681. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81682. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81683. }
  81684. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81685. // Alpha test
  81686. if (material && material.needAlphaTesting()) {
  81687. var alphaTexture = material.getAlphaTestTexture();
  81688. if (alphaTexture) {
  81689. this._effect.setTexture("diffuseSampler", alphaTexture);
  81690. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81691. }
  81692. }
  81693. engine.setZOffset(-this.zOffset);
  81694. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81695. engine.setZOffset(0);
  81696. };
  81697. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81698. var defines = [];
  81699. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81700. var mesh = subMesh.getMesh();
  81701. var material = subMesh.getMaterial();
  81702. if (material) {
  81703. // Alpha test
  81704. if (material.needAlphaTesting()) {
  81705. defines.push("#define ALPHATEST");
  81706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81707. attribs.push(BABYLON.VertexBuffer.UVKind);
  81708. defines.push("#define UV1");
  81709. }
  81710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81711. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81712. defines.push("#define UV2");
  81713. }
  81714. }
  81715. //Logarithmic depth
  81716. if (material.useLogarithmicDepth) {
  81717. defines.push("#define LOGARITHMICDEPTH");
  81718. }
  81719. }
  81720. // Bones
  81721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81722. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81723. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81724. if (mesh.numBoneInfluencers > 4) {
  81725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81727. }
  81728. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81729. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81730. }
  81731. else {
  81732. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81733. }
  81734. // Instances
  81735. if (useInstances) {
  81736. defines.push("#define INSTANCES");
  81737. attribs.push("world0");
  81738. attribs.push("world1");
  81739. attribs.push("world2");
  81740. attribs.push("world3");
  81741. }
  81742. // Get correct effect
  81743. var join = defines.join("\n");
  81744. if (this._cachedDefines !== join) {
  81745. this._cachedDefines = join;
  81746. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81747. }
  81748. return this._effect.isReady();
  81749. };
  81750. return OutlineRenderer;
  81751. }());
  81752. BABYLON.OutlineRenderer = OutlineRenderer;
  81753. })(BABYLON || (BABYLON = {}));
  81754. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81755. var BABYLON;
  81756. (function (BABYLON) {
  81757. var FaceAdjacencies = /** @class */ (function () {
  81758. function FaceAdjacencies() {
  81759. this.edges = new Array();
  81760. this.edgesConnectedCount = 0;
  81761. }
  81762. return FaceAdjacencies;
  81763. }());
  81764. var EdgesRenderer = /** @class */ (function () {
  81765. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81766. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81767. if (epsilon === void 0) { epsilon = 0.95; }
  81768. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81769. this.edgesWidthScalerForOrthographic = 1000.0;
  81770. this.edgesWidthScalerForPerspective = 50.0;
  81771. this._linesPositions = new Array();
  81772. this._linesNormals = new Array();
  81773. this._linesIndices = new Array();
  81774. this._buffers = {};
  81775. this._checkVerticesInsteadOfIndices = false;
  81776. this._source = source;
  81777. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81778. this._epsilon = epsilon;
  81779. this._prepareRessources();
  81780. this._generateEdgesLines();
  81781. }
  81782. EdgesRenderer.prototype._prepareRessources = function () {
  81783. if (this._lineShader) {
  81784. return;
  81785. }
  81786. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81787. attributes: ["position", "normal"],
  81788. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81789. });
  81790. this._lineShader.disableDepthWrite = true;
  81791. this._lineShader.backFaceCulling = false;
  81792. };
  81793. EdgesRenderer.prototype._rebuild = function () {
  81794. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81795. if (buffer) {
  81796. buffer._rebuild();
  81797. }
  81798. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81799. if (buffer) {
  81800. buffer._rebuild();
  81801. }
  81802. var scene = this._source.getScene();
  81803. var engine = scene.getEngine();
  81804. this._ib = engine.createIndexBuffer(this._linesIndices);
  81805. };
  81806. EdgesRenderer.prototype.dispose = function () {
  81807. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81808. if (buffer) {
  81809. buffer.dispose();
  81810. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81811. }
  81812. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81813. if (buffer) {
  81814. buffer.dispose();
  81815. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81816. }
  81817. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81818. this._lineShader.dispose();
  81819. };
  81820. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81821. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81822. return 0;
  81823. }
  81824. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81825. return 1;
  81826. }
  81827. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81828. return 2;
  81829. }
  81830. return -1;
  81831. };
  81832. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81833. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81834. return 0;
  81835. }
  81836. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81837. return 1;
  81838. }
  81839. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81840. return 2;
  81841. }
  81842. return -1;
  81843. };
  81844. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81845. var needToCreateLine;
  81846. if (edge === undefined) {
  81847. needToCreateLine = true;
  81848. }
  81849. else {
  81850. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81851. needToCreateLine = dotProduct < this._epsilon;
  81852. }
  81853. if (needToCreateLine) {
  81854. var offset = this._linesPositions.length / 3;
  81855. var normal = p0.subtract(p1);
  81856. normal.normalize();
  81857. // Positions
  81858. this._linesPositions.push(p0.x);
  81859. this._linesPositions.push(p0.y);
  81860. this._linesPositions.push(p0.z);
  81861. this._linesPositions.push(p0.x);
  81862. this._linesPositions.push(p0.y);
  81863. this._linesPositions.push(p0.z);
  81864. this._linesPositions.push(p1.x);
  81865. this._linesPositions.push(p1.y);
  81866. this._linesPositions.push(p1.z);
  81867. this._linesPositions.push(p1.x);
  81868. this._linesPositions.push(p1.y);
  81869. this._linesPositions.push(p1.z);
  81870. // Normals
  81871. this._linesNormals.push(p1.x);
  81872. this._linesNormals.push(p1.y);
  81873. this._linesNormals.push(p1.z);
  81874. this._linesNormals.push(-1);
  81875. this._linesNormals.push(p1.x);
  81876. this._linesNormals.push(p1.y);
  81877. this._linesNormals.push(p1.z);
  81878. this._linesNormals.push(1);
  81879. this._linesNormals.push(p0.x);
  81880. this._linesNormals.push(p0.y);
  81881. this._linesNormals.push(p0.z);
  81882. this._linesNormals.push(-1);
  81883. this._linesNormals.push(p0.x);
  81884. this._linesNormals.push(p0.y);
  81885. this._linesNormals.push(p0.z);
  81886. this._linesNormals.push(1);
  81887. // Indices
  81888. this._linesIndices.push(offset);
  81889. this._linesIndices.push(offset + 1);
  81890. this._linesIndices.push(offset + 2);
  81891. this._linesIndices.push(offset);
  81892. this._linesIndices.push(offset + 2);
  81893. this._linesIndices.push(offset + 3);
  81894. }
  81895. };
  81896. EdgesRenderer.prototype._generateEdgesLines = function () {
  81897. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81898. var indices = this._source.getIndices();
  81899. if (!indices || !positions) {
  81900. return;
  81901. }
  81902. // First let's find adjacencies
  81903. var adjacencies = new Array();
  81904. var faceNormals = new Array();
  81905. var index;
  81906. var faceAdjacencies;
  81907. // Prepare faces
  81908. for (index = 0; index < indices.length; index += 3) {
  81909. faceAdjacencies = new FaceAdjacencies();
  81910. var p0Index = indices[index];
  81911. var p1Index = indices[index + 1];
  81912. var p2Index = indices[index + 2];
  81913. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  81914. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  81915. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  81916. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  81917. faceNormal.normalize();
  81918. faceNormals.push(faceNormal);
  81919. adjacencies.push(faceAdjacencies);
  81920. }
  81921. // Scan
  81922. for (index = 0; index < adjacencies.length; index++) {
  81923. faceAdjacencies = adjacencies[index];
  81924. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  81925. var otherFaceAdjacencies = adjacencies[otherIndex];
  81926. if (faceAdjacencies.edgesConnectedCount === 3) {
  81927. break;
  81928. }
  81929. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  81930. continue;
  81931. }
  81932. var otherP0 = indices[otherIndex * 3];
  81933. var otherP1 = indices[otherIndex * 3 + 1];
  81934. var otherP2 = indices[otherIndex * 3 + 2];
  81935. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  81936. var otherEdgeIndex = 0;
  81937. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  81938. continue;
  81939. }
  81940. switch (edgeIndex) {
  81941. case 0:
  81942. if (this._checkVerticesInsteadOfIndices) {
  81943. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81944. }
  81945. else {
  81946. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  81947. }
  81948. break;
  81949. case 1:
  81950. if (this._checkVerticesInsteadOfIndices) {
  81951. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81952. }
  81953. else {
  81954. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  81955. }
  81956. break;
  81957. case 2:
  81958. if (this._checkVerticesInsteadOfIndices) {
  81959. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81960. }
  81961. else {
  81962. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  81963. }
  81964. break;
  81965. }
  81966. if (otherEdgeIndex === -1) {
  81967. continue;
  81968. }
  81969. faceAdjacencies.edges[edgeIndex] = otherIndex;
  81970. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  81971. faceAdjacencies.edgesConnectedCount++;
  81972. otherFaceAdjacencies.edgesConnectedCount++;
  81973. if (faceAdjacencies.edgesConnectedCount === 3) {
  81974. break;
  81975. }
  81976. }
  81977. }
  81978. }
  81979. // Create lines
  81980. for (index = 0; index < adjacencies.length; index++) {
  81981. // 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
  81982. var current = adjacencies[index];
  81983. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  81984. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  81985. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  81986. }
  81987. // Merge into a single mesh
  81988. var engine = this._source.getScene().getEngine();
  81989. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  81990. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  81991. this._ib = engine.createIndexBuffer(this._linesIndices);
  81992. this._indicesCount = this._linesIndices.length;
  81993. };
  81994. EdgesRenderer.prototype.render = function () {
  81995. var scene = this._source.getScene();
  81996. if (!this._lineShader.isReady() || !scene.activeCamera) {
  81997. return;
  81998. }
  81999. var engine = scene.getEngine();
  82000. this._lineShader._preBind();
  82001. // VBOs
  82002. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82003. scene.resetCachedMaterial();
  82004. this._lineShader.setColor4("color", this._source.edgesColor);
  82005. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82006. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82007. }
  82008. else {
  82009. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82010. }
  82011. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82012. this._lineShader.bind(this._source.getWorldMatrix());
  82013. // Draw order
  82014. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82015. this._lineShader.unbind();
  82016. engine.setDepthWrite(true);
  82017. };
  82018. return EdgesRenderer;
  82019. }());
  82020. BABYLON.EdgesRenderer = EdgesRenderer;
  82021. })(BABYLON || (BABYLON = {}));
  82022. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82023. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82024. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82025. s = arguments[i];
  82026. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82027. t[p] = s[p];
  82028. }
  82029. return t;
  82030. };
  82031. var BABYLON;
  82032. (function (BABYLON) {
  82033. /**
  82034. * The effect layer Helps adding post process effect blended with the main pass.
  82035. *
  82036. * This can be for instance use to generate glow or higlight effects on the scene.
  82037. *
  82038. * The effect layer class can not be used directly and is intented to inherited from to be
  82039. * customized per effects.
  82040. */
  82041. var EffectLayer = /** @class */ (function () {
  82042. /**
  82043. * Instantiates a new effect Layer and references it in the scene.
  82044. * @param name The name of the layer
  82045. * @param scene The scene to use the layer in
  82046. */
  82047. function EffectLayer(
  82048. /** The Friendly of the effect in the scene */
  82049. name, scene) {
  82050. this.name = name;
  82051. this._vertexBuffers = {};
  82052. this._maxSize = 0;
  82053. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82054. this._shouldRender = true;
  82055. this._postProcesses = [];
  82056. this._textures = [];
  82057. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82058. /**
  82059. * The clear color of the texture used to generate the glow map.
  82060. */
  82061. this.neutralColor = new BABYLON.Color4();
  82062. /**
  82063. * Specifies wether the highlight layer is enabled or not.
  82064. */
  82065. this.isEnabled = true;
  82066. /**
  82067. * An event triggered when the effect layer has been disposed.
  82068. */
  82069. this.onDisposeObservable = new BABYLON.Observable();
  82070. /**
  82071. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82072. */
  82073. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82074. /**
  82075. * An event triggered when the generated texture is being merged in the scene.
  82076. */
  82077. this.onBeforeComposeObservable = new BABYLON.Observable();
  82078. /**
  82079. * An event triggered when the generated texture has been merged in the scene.
  82080. */
  82081. this.onAfterComposeObservable = new BABYLON.Observable();
  82082. /**
  82083. * An event triggered when the efffect layer changes its size.
  82084. */
  82085. this.onSizeChangedObservable = new BABYLON.Observable();
  82086. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82087. this._engine = scene.getEngine();
  82088. this._maxSize = this._engine.getCaps().maxTextureSize;
  82089. this._scene.effectLayers.push(this);
  82090. // Generate Buffers
  82091. this._generateIndexBuffer();
  82092. this._genrateVertexBuffer();
  82093. }
  82094. Object.defineProperty(EffectLayer.prototype, "camera", {
  82095. /**
  82096. * Gets the camera attached to the layer.
  82097. */
  82098. get: function () {
  82099. return this._effectLayerOptions.camera;
  82100. },
  82101. enumerable: true,
  82102. configurable: true
  82103. });
  82104. /**
  82105. * Initializes the effect layer with the required options.
  82106. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82107. */
  82108. EffectLayer.prototype._init = function (options) {
  82109. // Adapt options
  82110. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82111. this._setMainTextureSize();
  82112. this._createMainTexture();
  82113. this._createTextureAndPostProcesses();
  82114. this._mergeEffect = this._createMergeEffect();
  82115. };
  82116. /**
  82117. * Generates the index buffer of the full screen quad blending to the main canvas.
  82118. */
  82119. EffectLayer.prototype._generateIndexBuffer = function () {
  82120. // Indices
  82121. var indices = [];
  82122. indices.push(0);
  82123. indices.push(1);
  82124. indices.push(2);
  82125. indices.push(0);
  82126. indices.push(2);
  82127. indices.push(3);
  82128. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82129. };
  82130. /**
  82131. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82132. */
  82133. EffectLayer.prototype._genrateVertexBuffer = function () {
  82134. // VBO
  82135. var vertices = [];
  82136. vertices.push(1, 1);
  82137. vertices.push(-1, 1);
  82138. vertices.push(-1, -1);
  82139. vertices.push(1, -1);
  82140. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82141. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82142. };
  82143. /**
  82144. * Sets the main texture desired size which is the closest power of two
  82145. * of the engine canvas size.
  82146. */
  82147. EffectLayer.prototype._setMainTextureSize = function () {
  82148. if (this._effectLayerOptions.mainTextureFixedSize) {
  82149. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82150. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82151. }
  82152. else {
  82153. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82154. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82155. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82156. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82157. }
  82158. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82159. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82160. };
  82161. /**
  82162. * Creates the main texture for the effect layer.
  82163. */
  82164. EffectLayer.prototype._createMainTexture = function () {
  82165. var _this = this;
  82166. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82167. width: this._mainTextureDesiredSize.width,
  82168. height: this._mainTextureDesiredSize.height
  82169. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82170. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82171. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82172. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82173. this._mainTexture.anisotropicFilteringLevel = 1;
  82174. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82175. this._mainTexture.renderParticles = false;
  82176. this._mainTexture.renderList = null;
  82177. this._mainTexture.ignoreCameraViewport = true;
  82178. // Custom render function
  82179. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82180. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82181. var index;
  82182. var engine = _this._scene.getEngine();
  82183. if (depthOnlySubMeshes.length) {
  82184. engine.setColorWrite(false);
  82185. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82186. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82187. }
  82188. engine.setColorWrite(true);
  82189. }
  82190. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82191. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82192. }
  82193. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82194. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82195. }
  82196. for (index = 0; index < transparentSubMeshes.length; index++) {
  82197. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82198. }
  82199. };
  82200. this._mainTexture.onClearObservable.add(function (engine) {
  82201. engine.clear(_this.neutralColor, true, true, true);
  82202. });
  82203. };
  82204. /**
  82205. * Checks for the readiness of the element composing the layer.
  82206. * @param subMesh the mesh to check for
  82207. * @param useInstances specify wether or not to use instances to render the mesh
  82208. * @param emissiveTexture the associated emissive texture used to generate the glow
  82209. * @return true if ready otherwise, false
  82210. */
  82211. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82212. var material = subMesh.getMaterial();
  82213. if (!material) {
  82214. return false;
  82215. }
  82216. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82217. return false;
  82218. }
  82219. var defines = [];
  82220. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82221. var mesh = subMesh.getMesh();
  82222. var uv1 = false;
  82223. var uv2 = false;
  82224. // Alpha test
  82225. if (material && material.needAlphaTesting()) {
  82226. var alphaTexture = material.getAlphaTestTexture();
  82227. if (alphaTexture) {
  82228. defines.push("#define ALPHATEST");
  82229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82230. alphaTexture.coordinatesIndex === 1) {
  82231. defines.push("#define DIFFUSEUV2");
  82232. uv2 = true;
  82233. }
  82234. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82235. defines.push("#define DIFFUSEUV1");
  82236. uv1 = true;
  82237. }
  82238. }
  82239. }
  82240. // Emissive
  82241. if (emissiveTexture) {
  82242. defines.push("#define EMISSIVE");
  82243. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82244. emissiveTexture.coordinatesIndex === 1) {
  82245. defines.push("#define EMISSIVEUV2");
  82246. uv2 = true;
  82247. }
  82248. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82249. defines.push("#define EMISSIVEUV1");
  82250. uv1 = true;
  82251. }
  82252. }
  82253. if (uv1) {
  82254. attribs.push(BABYLON.VertexBuffer.UVKind);
  82255. defines.push("#define UV1");
  82256. }
  82257. if (uv2) {
  82258. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82259. defines.push("#define UV2");
  82260. }
  82261. // Bones
  82262. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82263. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82264. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82265. if (mesh.numBoneInfluencers > 4) {
  82266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82268. }
  82269. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82270. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82271. }
  82272. else {
  82273. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82274. }
  82275. // Instances
  82276. if (useInstances) {
  82277. defines.push("#define INSTANCES");
  82278. attribs.push("world0");
  82279. attribs.push("world1");
  82280. attribs.push("world2");
  82281. attribs.push("world3");
  82282. }
  82283. // Get correct effect
  82284. var join = defines.join("\n");
  82285. if (this._cachedDefines !== join) {
  82286. this._cachedDefines = join;
  82287. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82288. }
  82289. return this._effectLayerMapGenerationEffect.isReady();
  82290. };
  82291. /**
  82292. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82293. */
  82294. EffectLayer.prototype.render = function () {
  82295. var currentEffect = this._mergeEffect;
  82296. // Check
  82297. if (!currentEffect.isReady())
  82298. return;
  82299. for (var i = 0; i < this._postProcesses.length; i++) {
  82300. if (!this._postProcesses[i].isReady()) {
  82301. return;
  82302. }
  82303. }
  82304. var engine = this._scene.getEngine();
  82305. this.onBeforeComposeObservable.notifyObservers(this);
  82306. // Render
  82307. engine.enableEffect(currentEffect);
  82308. engine.setState(false);
  82309. // VBOs
  82310. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82311. // Cache
  82312. var previousAlphaMode = engine.getAlphaMode();
  82313. // Go Blend.
  82314. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82315. // Blends the map on the main canvas.
  82316. this._internalRender(currentEffect);
  82317. // Restore Alpha
  82318. engine.setAlphaMode(previousAlphaMode);
  82319. this.onAfterComposeObservable.notifyObservers(this);
  82320. // Handle size changes.
  82321. var size = this._mainTexture.getSize();
  82322. this._setMainTextureSize();
  82323. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82324. // Recreate RTT and post processes on size change.
  82325. this.onSizeChangedObservable.notifyObservers(this);
  82326. this._disposeTextureAndPostProcesses();
  82327. this._createMainTexture();
  82328. this._createTextureAndPostProcesses();
  82329. }
  82330. };
  82331. /**
  82332. * Determine if a given mesh will be used in the current effect.
  82333. * @param mesh mesh to test
  82334. * @returns true if the mesh will be used
  82335. */
  82336. EffectLayer.prototype.hasMesh = function (mesh) {
  82337. return true;
  82338. };
  82339. /**
  82340. * Returns true if the layer contains information to display, otherwise false.
  82341. * @returns true if the glow layer should be rendered
  82342. */
  82343. EffectLayer.prototype.shouldRender = function () {
  82344. return this.isEnabled && this._shouldRender;
  82345. };
  82346. /**
  82347. * Returns true if the mesh should render, otherwise false.
  82348. * @param mesh The mesh to render
  82349. * @returns true if it should render otherwise false
  82350. */
  82351. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82352. return true;
  82353. };
  82354. /**
  82355. * Returns true if the mesh should render, otherwise false.
  82356. * @param mesh The mesh to render
  82357. * @returns true if it should render otherwise false
  82358. */
  82359. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82360. return true;
  82361. };
  82362. /**
  82363. * Renders the submesh passed in parameter to the generation map.
  82364. */
  82365. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82366. var _this = this;
  82367. if (!this.shouldRender()) {
  82368. return;
  82369. }
  82370. var material = subMesh.getMaterial();
  82371. var mesh = subMesh.getRenderingMesh();
  82372. var scene = this._scene;
  82373. var engine = scene.getEngine();
  82374. if (!material) {
  82375. return;
  82376. }
  82377. // Do not block in blend mode.
  82378. if (material.needAlphaBlendingForMesh(mesh)) {
  82379. return;
  82380. }
  82381. // Culling
  82382. engine.setState(material.backFaceCulling);
  82383. // Managing instances
  82384. var batch = mesh._getInstancesRenderList(subMesh._id);
  82385. if (batch.mustReturn) {
  82386. return;
  82387. }
  82388. // Early Exit per mesh
  82389. if (!this._shouldRenderMesh(mesh)) {
  82390. return;
  82391. }
  82392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82393. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82394. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82395. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82396. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82397. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82398. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82399. // Alpha test
  82400. if (material && material.needAlphaTesting()) {
  82401. var alphaTexture = material.getAlphaTestTexture();
  82402. if (alphaTexture) {
  82403. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82404. var textureMatrix = alphaTexture.getTextureMatrix();
  82405. if (textureMatrix) {
  82406. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82407. }
  82408. }
  82409. }
  82410. // Glow emissive only
  82411. if (this._emissiveTextureAndColor.texture) {
  82412. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82413. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82414. }
  82415. // Bones
  82416. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82417. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82418. }
  82419. // Draw
  82420. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82421. }
  82422. else {
  82423. // Need to reset refresh rate of the shadowMap
  82424. this._mainTexture.resetRefreshCounter();
  82425. }
  82426. };
  82427. /**
  82428. * Rebuild the required buffers.
  82429. * @ignore Internal use only.
  82430. */
  82431. EffectLayer.prototype._rebuild = function () {
  82432. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82433. if (vb) {
  82434. vb._rebuild();
  82435. }
  82436. this._generateIndexBuffer();
  82437. };
  82438. /**
  82439. * Dispose only the render target textures and post process.
  82440. */
  82441. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82442. this._mainTexture.dispose();
  82443. for (var i = 0; i < this._postProcesses.length; i++) {
  82444. if (this._postProcesses[i]) {
  82445. this._postProcesses[i].dispose();
  82446. }
  82447. }
  82448. this._postProcesses = [];
  82449. for (var i = 0; i < this._textures.length; i++) {
  82450. if (this._textures[i]) {
  82451. this._textures[i].dispose();
  82452. }
  82453. }
  82454. this._textures = [];
  82455. };
  82456. /**
  82457. * Dispose the highlight layer and free resources.
  82458. */
  82459. EffectLayer.prototype.dispose = function () {
  82460. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82461. if (vertexBuffer) {
  82462. vertexBuffer.dispose();
  82463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82464. }
  82465. if (this._indexBuffer) {
  82466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82467. this._indexBuffer = null;
  82468. }
  82469. // Clean textures and post processes
  82470. this._disposeTextureAndPostProcesses();
  82471. // Remove from scene
  82472. var index = this._scene.effectLayers.indexOf(this, 0);
  82473. if (index > -1) {
  82474. this._scene.effectLayers.splice(index, 1);
  82475. }
  82476. // Callback
  82477. this.onDisposeObservable.notifyObservers(this);
  82478. this.onDisposeObservable.clear();
  82479. this.onBeforeRenderMainTextureObservable.clear();
  82480. this.onBeforeComposeObservable.clear();
  82481. this.onAfterComposeObservable.clear();
  82482. this.onSizeChangedObservable.clear();
  82483. };
  82484. return EffectLayer;
  82485. }());
  82486. BABYLON.EffectLayer = EffectLayer;
  82487. })(BABYLON || (BABYLON = {}));
  82488. //# sourceMappingURL=babylon.effectLayer.js.map
  82489. var BABYLON;
  82490. (function (BABYLON) {
  82491. /**
  82492. * Special Glow Blur post process only blurring the alpha channel
  82493. * It enforces keeping the most luminous color in the color channel.
  82494. */
  82495. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82496. __extends(GlowBlurPostProcess, _super);
  82497. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82499. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82500. _this.direction = direction;
  82501. _this.kernel = kernel;
  82502. _this.onApplyObservable.add(function (effect) {
  82503. effect.setFloat2("screenSize", _this.width, _this.height);
  82504. effect.setVector2("direction", _this.direction);
  82505. effect.setFloat("blurWidth", _this.kernel);
  82506. });
  82507. return _this;
  82508. }
  82509. return GlowBlurPostProcess;
  82510. }(BABYLON.PostProcess));
  82511. /**
  82512. * The highlight layer Helps adding a glow effect around a mesh.
  82513. *
  82514. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82515. * glowy meshes to your scene.
  82516. *
  82517. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82518. */
  82519. var HighlightLayer = /** @class */ (function (_super) {
  82520. __extends(HighlightLayer, _super);
  82521. /**
  82522. * Instantiates a new highlight Layer and references it to the scene..
  82523. * @param name The name of the layer
  82524. * @param scene The scene to use the layer in
  82525. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82526. */
  82527. function HighlightLayer(name, scene, options) {
  82528. var _this = _super.call(this, name, scene) || this;
  82529. _this.name = name;
  82530. /**
  82531. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82532. */
  82533. _this.innerGlow = true;
  82534. /**
  82535. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82536. */
  82537. _this.outerGlow = true;
  82538. /**
  82539. * An event triggered when the highlight layer is being blurred.
  82540. */
  82541. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82542. /**
  82543. * An event triggered when the highlight layer has been blurred.
  82544. */
  82545. _this.onAfterBlurObservable = new BABYLON.Observable();
  82546. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82547. _this._meshes = {};
  82548. _this._excludedMeshes = {};
  82549. _this.neutralColor = HighlightLayer.NeutralColor;
  82550. // Warn on stencil
  82551. if (!_this._engine.isStencilEnable) {
  82552. 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 }");
  82553. }
  82554. // Adapt options
  82555. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82556. // Initialize the layer
  82557. _this._init({
  82558. alphaBlendingMode: _this._options.alphaBlendingMode,
  82559. camera: _this._options.camera,
  82560. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82561. mainTextureRatio: _this._options.mainTextureRatio
  82562. });
  82563. return _this;
  82564. }
  82565. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82566. /**
  82567. * Gets the horizontal size of the blur.
  82568. */
  82569. get: function () {
  82570. return this._horizontalBlurPostprocess.kernel;
  82571. },
  82572. /**
  82573. * Specifies the horizontal size of the blur.
  82574. */
  82575. set: function (value) {
  82576. this._horizontalBlurPostprocess.kernel = value;
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82582. /**
  82583. * Gets the vertical size of the blur.
  82584. */
  82585. get: function () {
  82586. return this._verticalBlurPostprocess.kernel;
  82587. },
  82588. /**
  82589. * Specifies the vertical size of the blur.
  82590. */
  82591. set: function (value) {
  82592. this._verticalBlurPostprocess.kernel = value;
  82593. },
  82594. enumerable: true,
  82595. configurable: true
  82596. });
  82597. /**
  82598. * Get the effect name of the layer.
  82599. * @return The effect name
  82600. */
  82601. HighlightLayer.prototype.getEffectName = function () {
  82602. return HighlightLayer.EffectName;
  82603. };
  82604. /**
  82605. * Create the merge effect. This is the shader use to blit the information back
  82606. * to the main canvas at the end of the scene rendering.
  82607. */
  82608. HighlightLayer.prototype._createMergeEffect = function () {
  82609. // Effect
  82610. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82611. };
  82612. /**
  82613. * Creates the render target textures and post processes used in the highlight layer.
  82614. */
  82615. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82616. var _this = this;
  82617. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82618. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82619. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82620. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82621. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82622. width: blurTextureWidth,
  82623. height: blurTextureHeight
  82624. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82625. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82626. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82627. this._blurTexture.anisotropicFilteringLevel = 16;
  82628. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82629. this._blurTexture.renderParticles = false;
  82630. this._blurTexture.ignoreCameraViewport = true;
  82631. this._textures = [this._blurTexture];
  82632. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82633. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82634. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82635. effect.setTexture("textureSampler", _this._mainTexture);
  82636. });
  82637. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82638. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82639. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82640. });
  82641. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82642. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82643. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82644. });
  82645. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82646. }
  82647. else {
  82648. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82649. width: blurTextureWidth,
  82650. height: blurTextureHeight
  82651. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82652. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82653. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82654. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82655. effect.setTexture("textureSampler", _this._mainTexture);
  82656. });
  82657. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82658. width: blurTextureWidth,
  82659. height: blurTextureHeight
  82660. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82661. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82662. }
  82663. this._mainTexture.onAfterUnbindObservable.add(function () {
  82664. _this.onBeforeBlurObservable.notifyObservers(_this);
  82665. var internalTexture = _this._blurTexture.getInternalTexture();
  82666. if (internalTexture) {
  82667. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82668. }
  82669. _this.onAfterBlurObservable.notifyObservers(_this);
  82670. });
  82671. // Prevent autoClear.
  82672. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82673. };
  82674. /**
  82675. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82676. */
  82677. HighlightLayer.prototype.needStencil = function () {
  82678. return true;
  82679. };
  82680. /**
  82681. * Checks for the readiness of the element composing the layer.
  82682. * @param subMesh the mesh to check for
  82683. * @param useInstances specify wether or not to use instances to render the mesh
  82684. * @param emissiveTexture the associated emissive texture used to generate the glow
  82685. * @return true if ready otherwise, false
  82686. */
  82687. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82688. var material = subMesh.getMaterial();
  82689. var mesh = subMesh.getRenderingMesh();
  82690. if (!material || !mesh || !this._meshes) {
  82691. return false;
  82692. }
  82693. var emissiveTexture = null;
  82694. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82695. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82696. emissiveTexture = material.emissiveTexture;
  82697. }
  82698. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82699. };
  82700. /**
  82701. * Implementation specific of rendering the generating effect on the main canvas.
  82702. * @param effect The effect used to render through
  82703. */
  82704. HighlightLayer.prototype._internalRender = function (effect) {
  82705. // Texture
  82706. effect.setTexture("textureSampler", this._blurTexture);
  82707. // Cache
  82708. var engine = this._engine;
  82709. var previousStencilBuffer = engine.getStencilBuffer();
  82710. var previousStencilFunction = engine.getStencilFunction();
  82711. var previousStencilMask = engine.getStencilMask();
  82712. var previousStencilOperationPass = engine.getStencilOperationPass();
  82713. var previousStencilOperationFail = engine.getStencilOperationFail();
  82714. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82715. // Stencil operations
  82716. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82717. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82718. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82719. // Draw order
  82720. engine.setStencilMask(0x00);
  82721. engine.setStencilBuffer(true);
  82722. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82723. // 2 passes inner outer
  82724. if (this.outerGlow) {
  82725. effect.setFloat("offset", 0);
  82726. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82727. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82728. }
  82729. if (this.innerGlow) {
  82730. effect.setFloat("offset", 1);
  82731. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82732. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82733. }
  82734. // Restore Cache
  82735. engine.setStencilFunction(previousStencilFunction);
  82736. engine.setStencilMask(previousStencilMask);
  82737. engine.setStencilBuffer(previousStencilBuffer);
  82738. engine.setStencilOperationPass(previousStencilOperationPass);
  82739. engine.setStencilOperationFail(previousStencilOperationFail);
  82740. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82741. };
  82742. /**
  82743. * Returns true if the layer contains information to display, otherwise false.
  82744. */
  82745. HighlightLayer.prototype.shouldRender = function () {
  82746. if (_super.prototype.shouldRender.call(this)) {
  82747. return this._meshes ? true : false;
  82748. }
  82749. return false;
  82750. };
  82751. /**
  82752. * Returns true if the mesh should render, otherwise false.
  82753. * @param mesh The mesh to render
  82754. * @returns true if it should render otherwise false
  82755. */
  82756. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  82757. // Excluded Mesh
  82758. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  82759. return false;
  82760. }
  82761. ;
  82762. return true;
  82763. };
  82764. /**
  82765. * Sets the required values for both the emissive texture and and the main color.
  82766. */
  82767. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  82768. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82769. if (highlightLayerMesh) {
  82770. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  82771. }
  82772. else {
  82773. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  82774. }
  82775. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82776. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  82777. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  82778. }
  82779. else {
  82780. this._emissiveTextureAndColor.texture = null;
  82781. }
  82782. };
  82783. /**
  82784. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82785. * @param mesh The mesh to exclude from the highlight layer
  82786. */
  82787. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82788. if (!this._excludedMeshes) {
  82789. return;
  82790. }
  82791. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82792. if (!meshExcluded) {
  82793. this._excludedMeshes[mesh.uniqueId] = {
  82794. mesh: mesh,
  82795. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82796. mesh.getEngine().setStencilBuffer(false);
  82797. }),
  82798. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82799. mesh.getEngine().setStencilBuffer(true);
  82800. }),
  82801. };
  82802. }
  82803. };
  82804. /**
  82805. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82806. * @param mesh The mesh to highlight
  82807. */
  82808. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82809. if (!this._excludedMeshes) {
  82810. return;
  82811. }
  82812. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82813. if (meshExcluded) {
  82814. if (meshExcluded.beforeRender) {
  82815. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82816. }
  82817. if (meshExcluded.afterRender) {
  82818. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82819. }
  82820. }
  82821. this._excludedMeshes[mesh.uniqueId] = null;
  82822. };
  82823. /**
  82824. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82825. * @param mesh mesh to test
  82826. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82827. */
  82828. HighlightLayer.prototype.hasMesh = function (mesh) {
  82829. if (!this._meshes) {
  82830. return false;
  82831. }
  82832. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82833. };
  82834. /**
  82835. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82836. * @param mesh The mesh to highlight
  82837. * @param color The color of the highlight
  82838. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82839. */
  82840. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82841. var _this = this;
  82842. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82843. if (!this._meshes) {
  82844. return;
  82845. }
  82846. var meshHighlight = this._meshes[mesh.uniqueId];
  82847. if (meshHighlight) {
  82848. meshHighlight.color = color;
  82849. }
  82850. else {
  82851. this._meshes[mesh.uniqueId] = {
  82852. mesh: mesh,
  82853. color: color,
  82854. // Lambda required for capture due to Observable this context
  82855. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82856. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82857. _this._defaultStencilReference(mesh);
  82858. }
  82859. else {
  82860. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82861. }
  82862. }),
  82863. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  82864. glowEmissiveOnly: glowEmissiveOnly
  82865. };
  82866. }
  82867. this._shouldRender = true;
  82868. };
  82869. /**
  82870. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82871. * @param mesh The mesh to highlight
  82872. */
  82873. HighlightLayer.prototype.removeMesh = function (mesh) {
  82874. if (!this._meshes) {
  82875. return;
  82876. }
  82877. var meshHighlight = this._meshes[mesh.uniqueId];
  82878. if (meshHighlight) {
  82879. if (meshHighlight.observerHighlight) {
  82880. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82881. }
  82882. if (meshHighlight.observerDefault) {
  82883. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82884. }
  82885. delete this._meshes[mesh.uniqueId];
  82886. }
  82887. this._shouldRender = false;
  82888. for (var meshHighlightToCheck in this._meshes) {
  82889. if (this._meshes[meshHighlightToCheck]) {
  82890. this._shouldRender = true;
  82891. break;
  82892. }
  82893. }
  82894. };
  82895. /**
  82896. * Force the stencil to the normal expected value for none glowing parts
  82897. */
  82898. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  82899. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  82900. };
  82901. /**
  82902. * Free any resources and references associated to a mesh.
  82903. * Internal use
  82904. * @param mesh The mesh to free.
  82905. */
  82906. HighlightLayer.prototype._disposeMesh = function (mesh) {
  82907. this.removeMesh(mesh);
  82908. this.removeExcludedMesh(mesh);
  82909. };
  82910. /**
  82911. * Dispose the highlight layer and free resources.
  82912. */
  82913. HighlightLayer.prototype.dispose = function () {
  82914. if (this._meshes) {
  82915. // Clean mesh references
  82916. for (var id in this._meshes) {
  82917. var meshHighlight = this._meshes[id];
  82918. if (meshHighlight && meshHighlight.mesh) {
  82919. if (meshHighlight.observerHighlight) {
  82920. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82921. }
  82922. if (meshHighlight.observerDefault) {
  82923. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82924. }
  82925. }
  82926. }
  82927. this._meshes = null;
  82928. }
  82929. if (this._excludedMeshes) {
  82930. for (var id in this._excludedMeshes) {
  82931. var meshHighlight = this._excludedMeshes[id];
  82932. if (meshHighlight) {
  82933. if (meshHighlight.beforeRender) {
  82934. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  82935. }
  82936. if (meshHighlight.afterRender) {
  82937. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  82938. }
  82939. }
  82940. }
  82941. this._excludedMeshes = null;
  82942. }
  82943. _super.prototype.dispose.call(this);
  82944. };
  82945. /**
  82946. * Effect Name of the highlight layer.
  82947. */
  82948. HighlightLayer.EffectName = "HighlightLayer";
  82949. /**
  82950. * The neutral color used during the preparation of the glow effect.
  82951. * This is black by default as the blend operation is a blend operation.
  82952. */
  82953. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  82954. /**
  82955. * Stencil value used for glowing meshes.
  82956. */
  82957. HighlightLayer.GlowingMeshStencilReference = 0x02;
  82958. /**
  82959. * Stencil value used for the other meshes in the scene.
  82960. */
  82961. HighlightLayer.NormalMeshStencilReference = 0x01;
  82962. return HighlightLayer;
  82963. }(BABYLON.EffectLayer));
  82964. BABYLON.HighlightLayer = HighlightLayer;
  82965. })(BABYLON || (BABYLON = {}));
  82966. //# sourceMappingURL=babylon.highlightLayer.js.map
  82967. var BABYLON;
  82968. (function (BABYLON) {
  82969. /**
  82970. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  82971. *
  82972. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82973. * glowy meshes to your scene.
  82974. *
  82975. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  82976. */
  82977. var GlowLayer = /** @class */ (function (_super) {
  82978. __extends(GlowLayer, _super);
  82979. /**
  82980. * Instantiates a new glow Layer and references it to the scene.
  82981. * @param name The name of the layer
  82982. * @param scene The scene to use the layer in
  82983. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  82984. */
  82985. function GlowLayer(name, scene, options) {
  82986. var _this = _super.call(this, name, scene) || this;
  82987. _this.name = name;
  82988. _this._intensity = 1.0;
  82989. _this._includedOnlyMeshes = [];
  82990. _this._excludedMeshes = [];
  82991. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  82992. // Adapt options
  82993. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  82994. // Initialize the layer
  82995. _this._init({
  82996. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  82997. camera: _this._options.camera,
  82998. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82999. mainTextureRatio: _this._options.mainTextureRatio
  83000. });
  83001. return _this;
  83002. }
  83003. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83004. /**
  83005. * Gets the kernel size of the blur.
  83006. */
  83007. get: function () {
  83008. return this._horizontalBlurPostprocess1.kernel;
  83009. },
  83010. /**
  83011. * Sets the kernel size of the blur.
  83012. */
  83013. set: function (value) {
  83014. this._horizontalBlurPostprocess1.kernel = value;
  83015. this._verticalBlurPostprocess1.kernel = value;
  83016. this._horizontalBlurPostprocess2.kernel = value;
  83017. this._verticalBlurPostprocess2.kernel = value;
  83018. },
  83019. enumerable: true,
  83020. configurable: true
  83021. });
  83022. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83023. /**
  83024. * Gets the glow intensity.
  83025. */
  83026. get: function () {
  83027. return this._intensity;
  83028. },
  83029. /**
  83030. * Sets the glow intensity.
  83031. */
  83032. set: function (value) {
  83033. this._intensity = value;
  83034. },
  83035. enumerable: true,
  83036. configurable: true
  83037. });
  83038. /**
  83039. * Get the effect name of the layer.
  83040. * @return The effect name
  83041. */
  83042. GlowLayer.prototype.getEffectName = function () {
  83043. return GlowLayer.EffectName;
  83044. };
  83045. /**
  83046. * Create the merge effect. This is the shader use to blit the information back
  83047. * to the main canvas at the end of the scene rendering.
  83048. */
  83049. GlowLayer.prototype._createMergeEffect = function () {
  83050. // Effect
  83051. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83052. };
  83053. /**
  83054. * Creates the render target textures and post processes used in the glow layer.
  83055. */
  83056. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83057. var _this = this;
  83058. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83059. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83060. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83061. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83062. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83063. width: blurTextureWidth,
  83064. height: blurTextureHeight
  83065. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83066. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83067. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83068. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83069. this._blurTexture1.renderParticles = false;
  83070. this._blurTexture1.ignoreCameraViewport = true;
  83071. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83072. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83073. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83074. width: blurTextureWidth2,
  83075. height: blurTextureHeight2
  83076. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83077. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83078. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83079. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83080. this._blurTexture2.renderParticles = false;
  83081. this._blurTexture2.ignoreCameraViewport = true;
  83082. this._textures = [this._blurTexture1, this._blurTexture2];
  83083. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83084. width: blurTextureWidth,
  83085. height: blurTextureHeight
  83086. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83087. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83088. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83089. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83090. effect.setTexture("textureSampler", _this._mainTexture);
  83091. });
  83092. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83093. width: blurTextureWidth,
  83094. height: blurTextureHeight
  83095. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83096. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83097. width: blurTextureWidth2,
  83098. height: blurTextureHeight2
  83099. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83100. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83101. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83102. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83103. effect.setTexture("textureSampler", _this._blurTexture1);
  83104. });
  83105. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83106. width: blurTextureWidth2,
  83107. height: blurTextureHeight2
  83108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83109. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83110. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83111. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83112. this._mainTexture.samples = this._options.mainTextureSamples;
  83113. this._mainTexture.onAfterUnbindObservable.add(function () {
  83114. var internalTexture = _this._blurTexture1.getInternalTexture();
  83115. if (internalTexture) {
  83116. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83117. internalTexture = _this._blurTexture2.getInternalTexture();
  83118. if (internalTexture) {
  83119. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83120. }
  83121. }
  83122. });
  83123. // Prevent autoClear.
  83124. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83125. };
  83126. /**
  83127. * Checks for the readiness of the element composing the layer.
  83128. * @param subMesh the mesh to check for
  83129. * @param useInstances specify wether or not to use instances to render the mesh
  83130. * @param emissiveTexture the associated emissive texture used to generate the glow
  83131. * @return true if ready otherwise, false
  83132. */
  83133. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83134. var material = subMesh.getMaterial();
  83135. var mesh = subMesh.getRenderingMesh();
  83136. if (!material || !mesh) {
  83137. return false;
  83138. }
  83139. var emissiveTexture = material.emissiveTexture;
  83140. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83141. };
  83142. /**
  83143. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83144. */
  83145. GlowLayer.prototype.needStencil = function () {
  83146. return false;
  83147. };
  83148. /**
  83149. * Implementation specific of rendering the generating effect on the main canvas.
  83150. * @param effect The effect used to render through
  83151. */
  83152. GlowLayer.prototype._internalRender = function (effect) {
  83153. // Texture
  83154. effect.setTexture("textureSampler", this._blurTexture1);
  83155. effect.setTexture("textureSampler2", this._blurTexture2);
  83156. effect.setFloat("offset", this._intensity);
  83157. // Cache
  83158. var engine = this._engine;
  83159. var previousStencilBuffer = engine.getStencilBuffer();
  83160. // Draw order
  83161. engine.setStencilBuffer(false);
  83162. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83163. // Draw order
  83164. engine.setStencilBuffer(previousStencilBuffer);
  83165. };
  83166. /**
  83167. * Sets the required values for both the emissive texture and and the main color.
  83168. */
  83169. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83170. var textureLevel = 1.0;
  83171. if (this.customEmissiveTextureSelector) {
  83172. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83173. }
  83174. else {
  83175. if (material) {
  83176. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83177. if (this._emissiveTextureAndColor.texture) {
  83178. textureLevel = this._emissiveTextureAndColor.texture.level;
  83179. }
  83180. }
  83181. else {
  83182. this._emissiveTextureAndColor.texture = null;
  83183. }
  83184. }
  83185. if (this.customEmissiveColorSelector) {
  83186. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83187. }
  83188. else {
  83189. if (material.emissiveColor) {
  83190. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83191. }
  83192. else {
  83193. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83194. }
  83195. }
  83196. };
  83197. /**
  83198. * Returns true if the mesh should render, otherwise false.
  83199. * @param mesh The mesh to render
  83200. * @returns true if it should render otherwise false
  83201. */
  83202. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83203. return this.hasMesh(mesh);
  83204. };
  83205. /**
  83206. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83207. * @param mesh The mesh to exclude from the glow layer
  83208. */
  83209. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83210. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83211. this._excludedMeshes.push(mesh.uniqueId);
  83212. }
  83213. };
  83214. /**
  83215. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83216. * @param mesh The mesh to remove
  83217. */
  83218. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83219. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83220. if (index !== -1) {
  83221. this._excludedMeshes.splice(index, 1);
  83222. }
  83223. };
  83224. /**
  83225. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83226. * @param mesh The mesh to include in the glow layer
  83227. */
  83228. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83229. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83230. this._includedOnlyMeshes.push(mesh.uniqueId);
  83231. }
  83232. };
  83233. /**
  83234. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83235. * @param mesh The mesh to remove
  83236. */
  83237. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83238. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83239. if (index !== -1) {
  83240. this._includedOnlyMeshes.splice(index, 1);
  83241. }
  83242. };
  83243. /**
  83244. * Determine if a given mesh will be used in the glow layer
  83245. * @param mesh The mesh to test
  83246. * @returns true if the mesh will be highlighted by the current glow layer
  83247. */
  83248. GlowLayer.prototype.hasMesh = function (mesh) {
  83249. // Included Mesh
  83250. if (this._includedOnlyMeshes.length) {
  83251. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83252. }
  83253. ;
  83254. // Excluded Mesh
  83255. if (this._excludedMeshes.length) {
  83256. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83257. }
  83258. ;
  83259. return true;
  83260. };
  83261. /**
  83262. * Free any resources and references associated to a mesh.
  83263. * Internal use
  83264. * @param mesh The mesh to free.
  83265. */
  83266. GlowLayer.prototype._disposeMesh = function (mesh) {
  83267. this.removeIncludedOnlyMesh(mesh);
  83268. this.removeExcludedMesh(mesh);
  83269. };
  83270. /**
  83271. * Effect Name of the layer.
  83272. */
  83273. GlowLayer.EffectName = "GlowLayer";
  83274. /**
  83275. * The default blur kernel size used for the glow.
  83276. */
  83277. GlowLayer.DefaultBlurKernelSize = 32;
  83278. /**
  83279. * The default texture size ratio used for the glow.
  83280. */
  83281. GlowLayer.DefaultTextureRatio = 0.5;
  83282. return GlowLayer;
  83283. }(BABYLON.EffectLayer));
  83284. BABYLON.GlowLayer = GlowLayer;
  83285. })(BABYLON || (BABYLON = {}));
  83286. //# sourceMappingURL=babylon.glowLayer.js.map
  83287. var BABYLON;
  83288. (function (BABYLON) {
  83289. /**
  83290. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83291. */
  83292. var AssetTaskState;
  83293. (function (AssetTaskState) {
  83294. /**
  83295. * Initialization
  83296. */
  83297. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83298. /**
  83299. * Running
  83300. */
  83301. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83302. /**
  83303. * Done
  83304. */
  83305. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83306. /**
  83307. * Error
  83308. */
  83309. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83310. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83311. /**
  83312. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83313. */
  83314. var AbstractAssetTask = /** @class */ (function () {
  83315. /**
  83316. * Creates a new {BABYLON.AssetsManager}
  83317. * @param name defines the name of the task
  83318. */
  83319. function AbstractAssetTask(
  83320. /**
  83321. * Task name
  83322. */ name) {
  83323. this.name = name;
  83324. this._isCompleted = false;
  83325. this._taskState = AssetTaskState.INIT;
  83326. }
  83327. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83328. /**
  83329. * Get if the task is completed
  83330. */
  83331. get: function () {
  83332. return this._isCompleted;
  83333. },
  83334. enumerable: true,
  83335. configurable: true
  83336. });
  83337. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83338. /**
  83339. * Gets the current state of the task
  83340. */
  83341. get: function () {
  83342. return this._taskState;
  83343. },
  83344. enumerable: true,
  83345. configurable: true
  83346. });
  83347. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83348. /**
  83349. * Gets the current error object (if task is in error)
  83350. */
  83351. get: function () {
  83352. return this._errorObject;
  83353. },
  83354. enumerable: true,
  83355. configurable: true
  83356. });
  83357. /**
  83358. * Internal only
  83359. * @ignore
  83360. */
  83361. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83362. if (this._errorObject) {
  83363. return;
  83364. }
  83365. this._errorObject = {
  83366. message: message,
  83367. exception: exception
  83368. };
  83369. };
  83370. /**
  83371. * Execute the current task
  83372. * @param scene defines the scene where you want your assets to be loaded
  83373. * @param onSuccess is a callback called when the task is successfully executed
  83374. * @param onError is a callback called if an error occurs
  83375. */
  83376. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83377. var _this = this;
  83378. this._taskState = AssetTaskState.RUNNING;
  83379. this.runTask(scene, function () {
  83380. _this.onDoneCallback(onSuccess, onError);
  83381. }, function (msg, exception) {
  83382. _this.onErrorCallback(onError, msg, exception);
  83383. });
  83384. };
  83385. /**
  83386. * Execute the current task
  83387. * @param scene defines the scene where you want your assets to be loaded
  83388. * @param onSuccess is a callback called when the task is successfully executed
  83389. * @param onError is a callback called if an error occurs
  83390. */
  83391. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83392. throw new Error("runTask is not implemented");
  83393. };
  83394. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83395. this._taskState = AssetTaskState.ERROR;
  83396. this._errorObject = {
  83397. message: message,
  83398. exception: exception
  83399. };
  83400. if (this.onError) {
  83401. this.onError(this, message, exception);
  83402. }
  83403. onError();
  83404. };
  83405. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83406. try {
  83407. this._taskState = AssetTaskState.DONE;
  83408. this._isCompleted = true;
  83409. if (this.onSuccess) {
  83410. this.onSuccess(this);
  83411. }
  83412. onSuccess();
  83413. }
  83414. catch (e) {
  83415. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83416. }
  83417. };
  83418. return AbstractAssetTask;
  83419. }());
  83420. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83421. /**
  83422. * Class used to share progress information about assets loading
  83423. */
  83424. var AssetsProgressEvent = /** @class */ (function () {
  83425. /**
  83426. * Creates a {BABYLON.AssetsProgressEvent}
  83427. * @param remainingCount defines the number of remaining tasks to process
  83428. * @param totalCount defines the total number of tasks
  83429. * @param task defines the task that was just processed
  83430. */
  83431. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83432. this.remainingCount = remainingCount;
  83433. this.totalCount = totalCount;
  83434. this.task = task;
  83435. }
  83436. return AssetsProgressEvent;
  83437. }());
  83438. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83439. /**
  83440. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83441. */
  83442. var MeshAssetTask = /** @class */ (function (_super) {
  83443. __extends(MeshAssetTask, _super);
  83444. /**
  83445. * Creates a new {BABYLON.MeshAssetTask}
  83446. * @param name defines the name of the task
  83447. * @param meshesNames defines the list of mesh's names you want to load
  83448. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83449. * @param sceneFilename defines the filename of the scene to load from
  83450. */
  83451. function MeshAssetTask(
  83452. /**
  83453. * Defines the name of the task
  83454. */
  83455. name,
  83456. /**
  83457. * Defines the list of mesh's names you want to load
  83458. */
  83459. meshesNames,
  83460. /**
  83461. * Defines the root url to use as a base to load your meshes and associated resources
  83462. */
  83463. rootUrl,
  83464. /**
  83465. * Defines the filename of the scene to load from
  83466. */
  83467. sceneFilename) {
  83468. var _this = _super.call(this, name) || this;
  83469. _this.name = name;
  83470. _this.meshesNames = meshesNames;
  83471. _this.rootUrl = rootUrl;
  83472. _this.sceneFilename = sceneFilename;
  83473. return _this;
  83474. }
  83475. /**
  83476. * Execute the current task
  83477. * @param scene defines the scene where you want your assets to be loaded
  83478. * @param onSuccess is a callback called when the task is successfully executed
  83479. * @param onError is a callback called if an error occurs
  83480. */
  83481. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83482. var _this = this;
  83483. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83484. _this.loadedMeshes = meshes;
  83485. _this.loadedParticleSystems = particleSystems;
  83486. _this.loadedSkeletons = skeletons;
  83487. onSuccess();
  83488. }, null, function (scene, message, exception) {
  83489. onError(message, exception);
  83490. });
  83491. };
  83492. return MeshAssetTask;
  83493. }(AbstractAssetTask));
  83494. BABYLON.MeshAssetTask = MeshAssetTask;
  83495. /**
  83496. * Define a task used by {BABYLON.AssetsManager} to load text content
  83497. */
  83498. var TextFileAssetTask = /** @class */ (function (_super) {
  83499. __extends(TextFileAssetTask, _super);
  83500. /**
  83501. * Creates a new TextFileAssetTask object
  83502. * @param name defines the name of the task
  83503. * @param url defines the location of the file to load
  83504. */
  83505. function TextFileAssetTask(
  83506. /**
  83507. * Defines the name of the task
  83508. */
  83509. name,
  83510. /**
  83511. * Defines the location of the file to load
  83512. */
  83513. url) {
  83514. var _this = _super.call(this, name) || this;
  83515. _this.name = name;
  83516. _this.url = url;
  83517. return _this;
  83518. }
  83519. /**
  83520. * Execute the current task
  83521. * @param scene defines the scene where you want your assets to be loaded
  83522. * @param onSuccess is a callback called when the task is successfully executed
  83523. * @param onError is a callback called if an error occurs
  83524. */
  83525. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83526. var _this = this;
  83527. scene._loadFile(this.url, function (data) {
  83528. _this.text = data;
  83529. onSuccess();
  83530. }, undefined, false, true, function (request, exception) {
  83531. if (request) {
  83532. onError(request.status + " " + request.statusText, exception);
  83533. }
  83534. });
  83535. };
  83536. return TextFileAssetTask;
  83537. }(AbstractAssetTask));
  83538. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83539. /**
  83540. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83541. */
  83542. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83543. __extends(BinaryFileAssetTask, _super);
  83544. /**
  83545. * Creates a new BinaryFileAssetTask object
  83546. * @param name defines the name of the new task
  83547. * @param url defines the location of the file to load
  83548. */
  83549. function BinaryFileAssetTask(
  83550. /**
  83551. * Defines the name of the task
  83552. */
  83553. name,
  83554. /**
  83555. * Defines the location of the file to load
  83556. */
  83557. url) {
  83558. var _this = _super.call(this, name) || this;
  83559. _this.name = name;
  83560. _this.url = url;
  83561. return _this;
  83562. }
  83563. /**
  83564. * Execute the current task
  83565. * @param scene defines the scene where you want your assets to be loaded
  83566. * @param onSuccess is a callback called when the task is successfully executed
  83567. * @param onError is a callback called if an error occurs
  83568. */
  83569. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83570. var _this = this;
  83571. scene._loadFile(this.url, function (data) {
  83572. _this.data = data;
  83573. onSuccess();
  83574. }, undefined, true, true, function (request, exception) {
  83575. if (request) {
  83576. onError(request.status + " " + request.statusText, exception);
  83577. }
  83578. });
  83579. };
  83580. return BinaryFileAssetTask;
  83581. }(AbstractAssetTask));
  83582. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83583. /**
  83584. * Define a task used by {BABYLON.AssetsManager} to load images
  83585. */
  83586. var ImageAssetTask = /** @class */ (function (_super) {
  83587. __extends(ImageAssetTask, _super);
  83588. /**
  83589. * Creates a new ImageAssetTask
  83590. * @param name defines the name of the task
  83591. * @param url defines the location of the image to load
  83592. */
  83593. function ImageAssetTask(
  83594. /**
  83595. * Defines the name of the task
  83596. */
  83597. name,
  83598. /**
  83599. * Defines the location of the image to load
  83600. */
  83601. url) {
  83602. var _this = _super.call(this, name) || this;
  83603. _this.name = name;
  83604. _this.url = url;
  83605. return _this;
  83606. }
  83607. /**
  83608. * Execute the current task
  83609. * @param scene defines the scene where you want your assets to be loaded
  83610. * @param onSuccess is a callback called when the task is successfully executed
  83611. * @param onError is a callback called if an error occurs
  83612. */
  83613. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83614. var _this = this;
  83615. var img = new Image();
  83616. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83617. img.onload = function () {
  83618. _this.image = img;
  83619. onSuccess();
  83620. };
  83621. img.onerror = function (err) {
  83622. onError("Error loading image", err);
  83623. };
  83624. img.src = this.url;
  83625. };
  83626. return ImageAssetTask;
  83627. }(AbstractAssetTask));
  83628. BABYLON.ImageAssetTask = ImageAssetTask;
  83629. /**
  83630. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83631. */
  83632. var TextureAssetTask = /** @class */ (function (_super) {
  83633. __extends(TextureAssetTask, _super);
  83634. /**
  83635. * Creates a new TextureAssetTask object
  83636. * @param name defines the name of the task
  83637. * @param url defines the location of the file to load
  83638. * @param noMipmap defines if mipmap should not be generated (default is false)
  83639. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83640. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83641. */
  83642. function TextureAssetTask(
  83643. /**
  83644. * Defines the name of the task
  83645. */
  83646. name,
  83647. /**
  83648. * Defines the location of the file to load
  83649. */
  83650. url,
  83651. /**
  83652. * Defines if mipmap should not be generated (default is false)
  83653. */
  83654. noMipmap,
  83655. /**
  83656. * Defines if texture must be inverted on Y axis (default is false)
  83657. */
  83658. invertY,
  83659. /**
  83660. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83661. */
  83662. samplingMode) {
  83663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83664. var _this = _super.call(this, name) || this;
  83665. _this.name = name;
  83666. _this.url = url;
  83667. _this.noMipmap = noMipmap;
  83668. _this.invertY = invertY;
  83669. _this.samplingMode = samplingMode;
  83670. return _this;
  83671. }
  83672. /**
  83673. * Execute the current task
  83674. * @param scene defines the scene where you want your assets to be loaded
  83675. * @param onSuccess is a callback called when the task is successfully executed
  83676. * @param onError is a callback called if an error occurs
  83677. */
  83678. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83679. var onload = function () {
  83680. onSuccess();
  83681. };
  83682. var onerror = function (message, exception) {
  83683. onError(message, exception);
  83684. };
  83685. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83686. };
  83687. return TextureAssetTask;
  83688. }(AbstractAssetTask));
  83689. BABYLON.TextureAssetTask = TextureAssetTask;
  83690. /**
  83691. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83692. */
  83693. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83694. __extends(CubeTextureAssetTask, _super);
  83695. /**
  83696. * Creates a new CubeTextureAssetTask
  83697. * @param name defines the name of the task
  83698. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83699. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83700. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83701. * @param files defines the explicit list of files (undefined by default)
  83702. */
  83703. function CubeTextureAssetTask(
  83704. /**
  83705. * Defines the name of the task
  83706. */
  83707. name,
  83708. /**
  83709. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83710. */
  83711. url,
  83712. /**
  83713. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83714. */
  83715. extensions,
  83716. /**
  83717. * Defines if mipmaps should not be generated (default is false)
  83718. */
  83719. noMipmap,
  83720. /**
  83721. * Defines the explicit list of files (undefined by default)
  83722. */
  83723. files) {
  83724. var _this = _super.call(this, name) || this;
  83725. _this.name = name;
  83726. _this.url = url;
  83727. _this.extensions = extensions;
  83728. _this.noMipmap = noMipmap;
  83729. _this.files = files;
  83730. return _this;
  83731. }
  83732. /**
  83733. * Execute the current task
  83734. * @param scene defines the scene where you want your assets to be loaded
  83735. * @param onSuccess is a callback called when the task is successfully executed
  83736. * @param onError is a callback called if an error occurs
  83737. */
  83738. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83739. var onload = function () {
  83740. onSuccess();
  83741. };
  83742. var onerror = function (message, exception) {
  83743. onError(message, exception);
  83744. };
  83745. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  83746. };
  83747. return CubeTextureAssetTask;
  83748. }(AbstractAssetTask));
  83749. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  83750. /**
  83751. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  83752. */
  83753. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  83754. __extends(HDRCubeTextureAssetTask, _super);
  83755. /**
  83756. * Creates a new HDRCubeTextureAssetTask object
  83757. * @param name defines the name of the task
  83758. * @param url defines the location of the file to load
  83759. * @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.
  83760. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83761. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83762. * @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)
  83763. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83764. */
  83765. function HDRCubeTextureAssetTask(
  83766. /**
  83767. * Defines the name of the task
  83768. */
  83769. name,
  83770. /**
  83771. * Defines the location of the file to load
  83772. */
  83773. url,
  83774. /**
  83775. * 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.
  83776. */
  83777. size,
  83778. /**
  83779. * Defines if mipmaps should not be generated (default is false)
  83780. */
  83781. noMipmap,
  83782. /**
  83783. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83784. */
  83785. generateHarmonics,
  83786. /**
  83787. * 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)
  83788. */
  83789. useInGammaSpace,
  83790. /**
  83791. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83792. */
  83793. usePMREMGenerator) {
  83794. if (noMipmap === void 0) { noMipmap = false; }
  83795. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83796. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83797. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83798. var _this = _super.call(this, name) || this;
  83799. _this.name = name;
  83800. _this.url = url;
  83801. _this.size = size;
  83802. _this.noMipmap = noMipmap;
  83803. _this.generateHarmonics = generateHarmonics;
  83804. _this.useInGammaSpace = useInGammaSpace;
  83805. _this.usePMREMGenerator = usePMREMGenerator;
  83806. return _this;
  83807. }
  83808. /**
  83809. * Execute the current task
  83810. * @param scene defines the scene where you want your assets to be loaded
  83811. * @param onSuccess is a callback called when the task is successfully executed
  83812. * @param onError is a callback called if an error occurs
  83813. */
  83814. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83815. var onload = function () {
  83816. onSuccess();
  83817. };
  83818. var onerror = function (message, exception) {
  83819. onError(message, exception);
  83820. };
  83821. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  83822. };
  83823. return HDRCubeTextureAssetTask;
  83824. }(AbstractAssetTask));
  83825. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  83826. /**
  83827. * This class can be used to easily import assets into a scene
  83828. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  83829. */
  83830. var AssetsManager = /** @class */ (function () {
  83831. /**
  83832. * Creates a new AssetsManager
  83833. * @param scene defines the scene to work on
  83834. */
  83835. function AssetsManager(scene) {
  83836. this._isLoading = false;
  83837. this._tasks = new Array();
  83838. this._waitingTasksCount = 0;
  83839. this._totalTasksCount = 0;
  83840. /**
  83841. * Observable called when all tasks are processed
  83842. */
  83843. this.onTaskSuccessObservable = new BABYLON.Observable();
  83844. /**
  83845. * Observable called when a task had an error
  83846. */
  83847. this.onTaskErrorObservable = new BABYLON.Observable();
  83848. /**
  83849. * Observable called when a task is successful
  83850. */
  83851. this.onTasksDoneObservable = new BABYLON.Observable();
  83852. /**
  83853. * Observable called when a task is done (whatever the result is)
  83854. */
  83855. this.onProgressObservable = new BABYLON.Observable();
  83856. /**
  83857. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  83858. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  83859. */
  83860. this.useDefaultLoadingScreen = true;
  83861. this._scene = scene;
  83862. }
  83863. /**
  83864. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  83865. * @param taskName defines the name of the new task
  83866. * @param meshesNames defines the name of meshes to load
  83867. * @param rootUrl defines the root url to use to locate files
  83868. * @param sceneFilename defines the filename of the scene file
  83869. * @returns a new {BABYLON.MeshAssetTask} object
  83870. */
  83871. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  83872. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  83873. this._tasks.push(task);
  83874. return task;
  83875. };
  83876. /**
  83877. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  83878. * @param taskName defines the name of the new task
  83879. * @param url defines the url of the file to load
  83880. * @returns a new {BABYLON.TextFileAssetTask} object
  83881. */
  83882. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  83883. var task = new TextFileAssetTask(taskName, url);
  83884. this._tasks.push(task);
  83885. return task;
  83886. };
  83887. /**
  83888. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  83889. * @param taskName defines the name of the new task
  83890. * @param url defines the url of the file to load
  83891. * @returns a new {BABYLON.BinaryFileAssetTask} object
  83892. */
  83893. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  83894. var task = new BinaryFileAssetTask(taskName, url);
  83895. this._tasks.push(task);
  83896. return task;
  83897. };
  83898. /**
  83899. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  83900. * @param taskName defines the name of the new task
  83901. * @param url defines the url of the file to load
  83902. * @returns a new {BABYLON.ImageAssetTask} object
  83903. */
  83904. AssetsManager.prototype.addImageTask = function (taskName, url) {
  83905. var task = new ImageAssetTask(taskName, url);
  83906. this._tasks.push(task);
  83907. return task;
  83908. };
  83909. /**
  83910. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  83911. * @param taskName defines the name of the new task
  83912. * @param url defines the url of the file to load
  83913. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83914. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  83915. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  83916. * @returns a new {BABYLON.TextureAssetTask} object
  83917. */
  83918. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  83919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83920. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  83921. this._tasks.push(task);
  83922. return task;
  83923. };
  83924. /**
  83925. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  83926. * @param taskName defines the name of the new task
  83927. * @param url defines the url of the file to load
  83928. * @param extensions defines the extension to use to load the cube map (can be null)
  83929. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83930. * @param files defines the list of files to load (can be null)
  83931. * @returns a new {BABYLON.CubeTextureAssetTask} object
  83932. */
  83933. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  83934. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  83935. this._tasks.push(task);
  83936. return task;
  83937. };
  83938. /**
  83939. *
  83940. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  83941. * @param taskName defines the name of the new task
  83942. * @param url defines the url of the file to load
  83943. * @param size defines the size you want for the cubemap (can be null)
  83944. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83945. * @param generateHarmonics defines if you want to automatically generate (true by default)
  83946. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  83947. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  83948. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  83949. */
  83950. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  83951. if (noMipmap === void 0) { noMipmap = false; }
  83952. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83953. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83954. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83955. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  83956. this._tasks.push(task);
  83957. return task;
  83958. };
  83959. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  83960. var _this = this;
  83961. this._waitingTasksCount--;
  83962. try {
  83963. if (task.taskState === AssetTaskState.DONE) {
  83964. // Let's remove successfull tasks
  83965. BABYLON.Tools.SetImmediate(function () {
  83966. var index = _this._tasks.indexOf(task);
  83967. if (index > -1) {
  83968. _this._tasks.splice(index, 1);
  83969. }
  83970. });
  83971. }
  83972. if (this.onProgress) {
  83973. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  83974. }
  83975. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  83976. }
  83977. catch (e) {
  83978. BABYLON.Tools.Error("Error running progress callbacks.");
  83979. console.log(e);
  83980. }
  83981. if (this._waitingTasksCount === 0) {
  83982. try {
  83983. if (this.onFinish) {
  83984. this.onFinish(this._tasks);
  83985. }
  83986. this.onTasksDoneObservable.notifyObservers(this._tasks);
  83987. }
  83988. catch (e) {
  83989. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  83990. console.log(e);
  83991. }
  83992. this._isLoading = false;
  83993. this._scene.getEngine().hideLoadingUI();
  83994. }
  83995. };
  83996. AssetsManager.prototype._runTask = function (task) {
  83997. var _this = this;
  83998. var done = function () {
  83999. try {
  84000. if (_this.onTaskSuccess) {
  84001. _this.onTaskSuccess(task);
  84002. }
  84003. _this.onTaskSuccessObservable.notifyObservers(task);
  84004. _this._decreaseWaitingTasksCount(task);
  84005. }
  84006. catch (e) {
  84007. error("Error executing task success callbacks", e);
  84008. }
  84009. };
  84010. var error = function (message, exception) {
  84011. task._setErrorObject(message, exception);
  84012. if (_this.onTaskError) {
  84013. _this.onTaskError(task);
  84014. }
  84015. _this.onTaskErrorObservable.notifyObservers(task);
  84016. _this._decreaseWaitingTasksCount(task);
  84017. };
  84018. task.run(this._scene, done, error);
  84019. };
  84020. /**
  84021. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84022. * @return the current instance of the {BABYLON.AssetsManager}
  84023. */
  84024. AssetsManager.prototype.reset = function () {
  84025. this._isLoading = false;
  84026. this._tasks = new Array();
  84027. return this;
  84028. };
  84029. /**
  84030. * Start the loading process
  84031. * @return the current instance of the {BABYLON.AssetsManager}
  84032. */
  84033. AssetsManager.prototype.load = function () {
  84034. if (this._isLoading) {
  84035. return this;
  84036. }
  84037. this._isLoading = true;
  84038. this._waitingTasksCount = this._tasks.length;
  84039. this._totalTasksCount = this._tasks.length;
  84040. if (this._waitingTasksCount === 0) {
  84041. if (this.onFinish) {
  84042. this.onFinish(this._tasks);
  84043. }
  84044. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84045. return this;
  84046. }
  84047. if (this.useDefaultLoadingScreen) {
  84048. this._scene.getEngine().displayLoadingUI();
  84049. }
  84050. for (var index = 0; index < this._tasks.length; index++) {
  84051. var task = this._tasks[index];
  84052. this._runTask(task);
  84053. }
  84054. return this;
  84055. };
  84056. return AssetsManager;
  84057. }());
  84058. BABYLON.AssetsManager = AssetsManager;
  84059. })(BABYLON || (BABYLON = {}));
  84060. //# sourceMappingURL=babylon.assetsManager.js.map
  84061. var BABYLON;
  84062. (function (BABYLON) {
  84063. var serializedGeometries = [];
  84064. var serializeGeometry = function (geometry, serializationGeometries) {
  84065. if (serializedGeometries[geometry.id]) {
  84066. return;
  84067. }
  84068. if (geometry.doNotSerialize) {
  84069. return;
  84070. }
  84071. if (geometry instanceof BABYLON.BoxGeometry) {
  84072. serializationGeometries.boxes.push(geometry.serialize());
  84073. }
  84074. else if (geometry instanceof BABYLON.SphereGeometry) {
  84075. serializationGeometries.spheres.push(geometry.serialize());
  84076. }
  84077. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84078. serializationGeometries.cylinders.push(geometry.serialize());
  84079. }
  84080. else if (geometry instanceof BABYLON.TorusGeometry) {
  84081. serializationGeometries.toruses.push(geometry.serialize());
  84082. }
  84083. else if (geometry instanceof BABYLON.GroundGeometry) {
  84084. serializationGeometries.grounds.push(geometry.serialize());
  84085. }
  84086. else if (geometry instanceof BABYLON.Plane) {
  84087. serializationGeometries.planes.push(geometry.serialize());
  84088. }
  84089. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84090. serializationGeometries.torusKnots.push(geometry.serialize());
  84091. }
  84092. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84093. throw new Error("Unknown primitive type");
  84094. }
  84095. else {
  84096. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84097. }
  84098. serializedGeometries[geometry.id] = true;
  84099. };
  84100. var serializeMesh = function (mesh, serializationScene) {
  84101. var serializationObject = {};
  84102. // Geometry
  84103. var geometry = mesh._geometry;
  84104. if (geometry) {
  84105. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84106. // 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
  84107. serializeGeometry(geometry, serializationScene.geometries);
  84108. }
  84109. }
  84110. // Custom
  84111. if (mesh.serialize) {
  84112. mesh.serialize(serializationObject);
  84113. }
  84114. return serializationObject;
  84115. };
  84116. var finalizeSingleMesh = function (mesh, serializationObject) {
  84117. //only works if the mesh is already loaded
  84118. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84119. //serialize material
  84120. if (mesh.material) {
  84121. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84122. serializationObject.materials = serializationObject.materials || [];
  84123. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84124. serializationObject.materials.push(mesh.material.serialize());
  84125. }
  84126. }
  84127. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84128. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84129. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84130. serializationObject.multiMaterials.push(mesh.material.serialize());
  84131. }
  84132. }
  84133. }
  84134. //serialize geometry
  84135. var geometry = mesh._geometry;
  84136. if (geometry) {
  84137. if (!serializationObject.geometries) {
  84138. serializationObject.geometries = {};
  84139. serializationObject.geometries.boxes = [];
  84140. serializationObject.geometries.spheres = [];
  84141. serializationObject.geometries.cylinders = [];
  84142. serializationObject.geometries.toruses = [];
  84143. serializationObject.geometries.grounds = [];
  84144. serializationObject.geometries.planes = [];
  84145. serializationObject.geometries.torusKnots = [];
  84146. serializationObject.geometries.vertexData = [];
  84147. }
  84148. serializeGeometry(geometry, serializationObject.geometries);
  84149. }
  84150. // Skeletons
  84151. if (mesh.skeleton) {
  84152. serializationObject.skeletons = serializationObject.skeletons || [];
  84153. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84154. }
  84155. //serialize the actual mesh
  84156. serializationObject.meshes = serializationObject.meshes || [];
  84157. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84158. }
  84159. };
  84160. var SceneSerializer = /** @class */ (function () {
  84161. function SceneSerializer() {
  84162. }
  84163. SceneSerializer.ClearCache = function () {
  84164. serializedGeometries = [];
  84165. };
  84166. SceneSerializer.Serialize = function (scene) {
  84167. var serializationObject = {};
  84168. SceneSerializer.ClearCache();
  84169. // Scene
  84170. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84171. serializationObject.autoClear = scene.autoClear;
  84172. serializationObject.clearColor = scene.clearColor.asArray();
  84173. serializationObject.ambientColor = scene.ambientColor.asArray();
  84174. serializationObject.gravity = scene.gravity.asArray();
  84175. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84176. serializationObject.workerCollisions = scene.workerCollisions;
  84177. // Fog
  84178. if (scene.fogMode && scene.fogMode !== 0) {
  84179. serializationObject.fogMode = scene.fogMode;
  84180. serializationObject.fogColor = scene.fogColor.asArray();
  84181. serializationObject.fogStart = scene.fogStart;
  84182. serializationObject.fogEnd = scene.fogEnd;
  84183. serializationObject.fogDensity = scene.fogDensity;
  84184. }
  84185. //Physics
  84186. if (scene.isPhysicsEnabled()) {
  84187. var physicEngine = scene.getPhysicsEngine();
  84188. if (physicEngine) {
  84189. serializationObject.physicsEnabled = true;
  84190. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84191. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84192. }
  84193. }
  84194. // Metadata
  84195. if (scene.metadata) {
  84196. serializationObject.metadata = scene.metadata;
  84197. }
  84198. // Morph targets
  84199. serializationObject.morphTargetManagers = [];
  84200. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84201. var abstractMesh = _a[_i];
  84202. var manager = abstractMesh.morphTargetManager;
  84203. if (manager) {
  84204. serializationObject.morphTargetManagers.push(manager.serialize());
  84205. }
  84206. }
  84207. // Lights
  84208. serializationObject.lights = [];
  84209. var index;
  84210. var light;
  84211. for (index = 0; index < scene.lights.length; index++) {
  84212. light = scene.lights[index];
  84213. if (!light.doNotSerialize) {
  84214. serializationObject.lights.push(light.serialize());
  84215. }
  84216. }
  84217. // Cameras
  84218. serializationObject.cameras = [];
  84219. for (index = 0; index < scene.cameras.length; index++) {
  84220. var camera = scene.cameras[index];
  84221. if (!camera.doNotSerialize) {
  84222. serializationObject.cameras.push(camera.serialize());
  84223. }
  84224. }
  84225. if (scene.activeCamera) {
  84226. serializationObject.activeCameraID = scene.activeCamera.id;
  84227. }
  84228. // Animations
  84229. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84230. // Materials
  84231. serializationObject.materials = [];
  84232. serializationObject.multiMaterials = [];
  84233. var material;
  84234. for (index = 0; index < scene.materials.length; index++) {
  84235. material = scene.materials[index];
  84236. if (!material.doNotSerialize) {
  84237. serializationObject.materials.push(material.serialize());
  84238. }
  84239. }
  84240. // MultiMaterials
  84241. serializationObject.multiMaterials = [];
  84242. for (index = 0; index < scene.multiMaterials.length; index++) {
  84243. var multiMaterial = scene.multiMaterials[index];
  84244. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84245. }
  84246. // Environment texture
  84247. if (scene.environmentTexture) {
  84248. serializationObject.environmentTexture = scene.environmentTexture.name;
  84249. }
  84250. // Skeletons
  84251. serializationObject.skeletons = [];
  84252. for (index = 0; index < scene.skeletons.length; index++) {
  84253. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84254. }
  84255. // Transform nodes
  84256. serializationObject.transformNodes = [];
  84257. for (index = 0; index < scene.transformNodes.length; index++) {
  84258. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84259. }
  84260. // Geometries
  84261. serializationObject.geometries = {};
  84262. serializationObject.geometries.boxes = [];
  84263. serializationObject.geometries.spheres = [];
  84264. serializationObject.geometries.cylinders = [];
  84265. serializationObject.geometries.toruses = [];
  84266. serializationObject.geometries.grounds = [];
  84267. serializationObject.geometries.planes = [];
  84268. serializationObject.geometries.torusKnots = [];
  84269. serializationObject.geometries.vertexData = [];
  84270. serializedGeometries = [];
  84271. var geometries = scene.getGeometries();
  84272. for (index = 0; index < geometries.length; index++) {
  84273. var geometry = geometries[index];
  84274. if (geometry.isReady()) {
  84275. serializeGeometry(geometry, serializationObject.geometries);
  84276. }
  84277. }
  84278. // Meshes
  84279. serializationObject.meshes = [];
  84280. for (index = 0; index < scene.meshes.length; index++) {
  84281. var abstractMesh = scene.meshes[index];
  84282. if (abstractMesh instanceof BABYLON.Mesh) {
  84283. var mesh = abstractMesh;
  84284. if (!mesh.doNotSerialize) {
  84285. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84286. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84287. }
  84288. }
  84289. }
  84290. }
  84291. // Particles Systems
  84292. serializationObject.particleSystems = [];
  84293. for (index = 0; index < scene.particleSystems.length; index++) {
  84294. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84295. }
  84296. // Lens flares
  84297. serializationObject.lensFlareSystems = [];
  84298. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84299. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84300. }
  84301. // Shadows
  84302. serializationObject.shadowGenerators = [];
  84303. for (index = 0; index < scene.lights.length; index++) {
  84304. light = scene.lights[index];
  84305. var shadowGenerator = light.getShadowGenerator();
  84306. if (shadowGenerator) {
  84307. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84308. }
  84309. }
  84310. // Action Manager
  84311. if (scene.actionManager) {
  84312. serializationObject.actions = scene.actionManager.serialize("scene");
  84313. }
  84314. // Audio
  84315. serializationObject.sounds = [];
  84316. for (index = 0; index < scene.soundTracks.length; index++) {
  84317. var soundtrack = scene.soundTracks[index];
  84318. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84319. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84320. }
  84321. }
  84322. return serializationObject;
  84323. };
  84324. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84325. if (withParents === void 0) { withParents = false; }
  84326. if (withChildren === void 0) { withChildren = false; }
  84327. var serializationObject = {};
  84328. SceneSerializer.ClearCache();
  84329. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84330. if (withParents || withChildren) {
  84331. //deliberate for loop! not for each, appended should be processed as well.
  84332. for (var i = 0; i < toSerialize.length; ++i) {
  84333. if (withChildren) {
  84334. toSerialize[i].getDescendants().forEach(function (node) {
  84335. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84336. toSerialize.push(node);
  84337. }
  84338. });
  84339. }
  84340. //make sure the array doesn't contain the object already
  84341. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84342. toSerialize.push(toSerialize[i].parent);
  84343. }
  84344. }
  84345. }
  84346. toSerialize.forEach(function (mesh) {
  84347. finalizeSingleMesh(mesh, serializationObject);
  84348. });
  84349. return serializationObject;
  84350. };
  84351. return SceneSerializer;
  84352. }());
  84353. BABYLON.SceneSerializer = SceneSerializer;
  84354. })(BABYLON || (BABYLON = {}));
  84355. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84356. var BABYLON;
  84357. (function (BABYLON) {
  84358. var ReflectionProbe = /** @class */ (function () {
  84359. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84360. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84361. var _this = this;
  84362. this.name = name;
  84363. this._viewMatrix = BABYLON.Matrix.Identity();
  84364. this._target = BABYLON.Vector3.Zero();
  84365. this._add = BABYLON.Vector3.Zero();
  84366. this.invertYAxis = false;
  84367. this.position = BABYLON.Vector3.Zero();
  84368. this._scene = scene;
  84369. this._scene.reflectionProbes.push(this);
  84370. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84371. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84372. switch (faceIndex) {
  84373. case 0:
  84374. _this._add.copyFromFloats(1, 0, 0);
  84375. break;
  84376. case 1:
  84377. _this._add.copyFromFloats(-1, 0, 0);
  84378. break;
  84379. case 2:
  84380. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84381. break;
  84382. case 3:
  84383. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84384. break;
  84385. case 4:
  84386. _this._add.copyFromFloats(0, 0, 1);
  84387. break;
  84388. case 5:
  84389. _this._add.copyFromFloats(0, 0, -1);
  84390. break;
  84391. }
  84392. if (_this._attachedMesh) {
  84393. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84394. }
  84395. _this.position.addToRef(_this._add, _this._target);
  84396. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84397. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84398. scene._forcedViewPosition = _this.position;
  84399. });
  84400. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84401. scene._forcedViewPosition = null;
  84402. scene.updateTransformMatrix(true);
  84403. });
  84404. if (scene.activeCamera) {
  84405. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84406. }
  84407. }
  84408. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84409. get: function () {
  84410. return this._renderTargetTexture.samples;
  84411. },
  84412. set: function (value) {
  84413. this._renderTargetTexture.samples = value;
  84414. },
  84415. enumerable: true,
  84416. configurable: true
  84417. });
  84418. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84419. get: function () {
  84420. return this._renderTargetTexture.refreshRate;
  84421. },
  84422. set: function (value) {
  84423. this._renderTargetTexture.refreshRate = value;
  84424. },
  84425. enumerable: true,
  84426. configurable: true
  84427. });
  84428. ReflectionProbe.prototype.getScene = function () {
  84429. return this._scene;
  84430. };
  84431. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84432. get: function () {
  84433. return this._renderTargetTexture;
  84434. },
  84435. enumerable: true,
  84436. configurable: true
  84437. });
  84438. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84439. get: function () {
  84440. return this._renderTargetTexture.renderList;
  84441. },
  84442. enumerable: true,
  84443. configurable: true
  84444. });
  84445. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84446. this._attachedMesh = mesh;
  84447. };
  84448. /**
  84449. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84450. *
  84451. * @param renderingGroupId The rendering group id corresponding to its index
  84452. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84453. */
  84454. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84455. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84456. };
  84457. ReflectionProbe.prototype.dispose = function () {
  84458. var index = this._scene.reflectionProbes.indexOf(this);
  84459. if (index !== -1) {
  84460. // Remove from the scene if found
  84461. this._scene.reflectionProbes.splice(index, 1);
  84462. }
  84463. if (this._renderTargetTexture) {
  84464. this._renderTargetTexture.dispose();
  84465. this._renderTargetTexture = null;
  84466. }
  84467. };
  84468. return ReflectionProbe;
  84469. }());
  84470. BABYLON.ReflectionProbe = ReflectionProbe;
  84471. })(BABYLON || (BABYLON = {}));
  84472. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84473. var BABYLON;
  84474. (function (BABYLON) {
  84475. var Layer = /** @class */ (function () {
  84476. function Layer(name, imgUrl, scene, isBackground, color) {
  84477. this.name = name;
  84478. this.scale = new BABYLON.Vector2(1, 1);
  84479. this.offset = new BABYLON.Vector2(0, 0);
  84480. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84481. this.layerMask = 0x0FFFFFFF;
  84482. this._vertexBuffers = {};
  84483. // Events
  84484. /**
  84485. * An event triggered when the layer is disposed.
  84486. * @type {BABYLON.Observable}
  84487. */
  84488. this.onDisposeObservable = new BABYLON.Observable();
  84489. /**
  84490. * An event triggered before rendering the scene
  84491. * @type {BABYLON.Observable}
  84492. */
  84493. this.onBeforeRenderObservable = new BABYLON.Observable();
  84494. /**
  84495. * An event triggered after rendering the scene
  84496. * @type {BABYLON.Observable}
  84497. */
  84498. this.onAfterRenderObservable = new BABYLON.Observable();
  84499. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84500. this.isBackground = isBackground === undefined ? true : isBackground;
  84501. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84502. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84503. this._scene.layers.push(this);
  84504. var engine = this._scene.getEngine();
  84505. // VBO
  84506. var vertices = [];
  84507. vertices.push(1, 1);
  84508. vertices.push(-1, 1);
  84509. vertices.push(-1, -1);
  84510. vertices.push(1, -1);
  84511. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84512. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84513. this._createIndexBuffer();
  84514. // Effects
  84515. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84516. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84517. }
  84518. Object.defineProperty(Layer.prototype, "onDispose", {
  84519. set: function (callback) {
  84520. if (this._onDisposeObserver) {
  84521. this.onDisposeObservable.remove(this._onDisposeObserver);
  84522. }
  84523. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84524. },
  84525. enumerable: true,
  84526. configurable: true
  84527. });
  84528. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84529. set: function (callback) {
  84530. if (this._onBeforeRenderObserver) {
  84531. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84532. }
  84533. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84534. },
  84535. enumerable: true,
  84536. configurable: true
  84537. });
  84538. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84539. set: function (callback) {
  84540. if (this._onAfterRenderObserver) {
  84541. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84542. }
  84543. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84544. },
  84545. enumerable: true,
  84546. configurable: true
  84547. });
  84548. Layer.prototype._createIndexBuffer = function () {
  84549. var engine = this._scene.getEngine();
  84550. // Indices
  84551. var indices = [];
  84552. indices.push(0);
  84553. indices.push(1);
  84554. indices.push(2);
  84555. indices.push(0);
  84556. indices.push(2);
  84557. indices.push(3);
  84558. this._indexBuffer = engine.createIndexBuffer(indices);
  84559. };
  84560. Layer.prototype._rebuild = function () {
  84561. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84562. if (vb) {
  84563. vb._rebuild();
  84564. }
  84565. this._createIndexBuffer();
  84566. };
  84567. Layer.prototype.render = function () {
  84568. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84569. // Check
  84570. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84571. return;
  84572. var engine = this._scene.getEngine();
  84573. this.onBeforeRenderObservable.notifyObservers(this);
  84574. // Render
  84575. engine.enableEffect(currentEffect);
  84576. engine.setState(false);
  84577. // Texture
  84578. currentEffect.setTexture("textureSampler", this.texture);
  84579. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84580. // Color
  84581. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84582. // Scale / offset
  84583. currentEffect.setVector2("offset", this.offset);
  84584. currentEffect.setVector2("scale", this.scale);
  84585. // VBOs
  84586. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84587. // Draw order
  84588. if (!this.alphaTest) {
  84589. engine.setAlphaMode(this.alphaBlendingMode);
  84590. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84591. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84592. }
  84593. else {
  84594. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84595. }
  84596. this.onAfterRenderObservable.notifyObservers(this);
  84597. };
  84598. Layer.prototype.dispose = function () {
  84599. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84600. if (vertexBuffer) {
  84601. vertexBuffer.dispose();
  84602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84603. }
  84604. if (this._indexBuffer) {
  84605. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84606. this._indexBuffer = null;
  84607. }
  84608. if (this.texture) {
  84609. this.texture.dispose();
  84610. this.texture = null;
  84611. }
  84612. // Remove from scene
  84613. var index = this._scene.layers.indexOf(this);
  84614. this._scene.layers.splice(index, 1);
  84615. // Callback
  84616. this.onDisposeObservable.notifyObservers(this);
  84617. this.onDisposeObservable.clear();
  84618. this.onAfterRenderObservable.clear();
  84619. this.onBeforeRenderObservable.clear();
  84620. };
  84621. return Layer;
  84622. }());
  84623. BABYLON.Layer = Layer;
  84624. })(BABYLON || (BABYLON = {}));
  84625. //# sourceMappingURL=babylon.layer.js.map
  84626. var BABYLON;
  84627. (function (BABYLON) {
  84628. var TextureTools = /** @class */ (function () {
  84629. function TextureTools() {
  84630. }
  84631. /**
  84632. * Uses the GPU to create a copy texture rescaled at a given size
  84633. * @param texture Texture to copy from
  84634. * @param width Desired width
  84635. * @param height Desired height
  84636. * @return Generated texture
  84637. */
  84638. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84639. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84640. var scene = texture.getScene();
  84641. var engine = scene.getEngine();
  84642. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84643. rtt.wrapU = texture.wrapU;
  84644. rtt.wrapV = texture.wrapV;
  84645. rtt.uOffset = texture.uOffset;
  84646. rtt.vOffset = texture.vOffset;
  84647. rtt.uScale = texture.uScale;
  84648. rtt.vScale = texture.vScale;
  84649. rtt.uAng = texture.uAng;
  84650. rtt.vAng = texture.vAng;
  84651. rtt.wAng = texture.wAng;
  84652. rtt.coordinatesIndex = texture.coordinatesIndex;
  84653. rtt.level = texture.level;
  84654. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84655. rtt._texture.isReady = false;
  84656. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84657. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84658. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84659. passPostProcess.getEffect().executeWhenCompiled(function () {
  84660. passPostProcess.onApply = function (effect) {
  84661. effect.setTexture("textureSampler", texture);
  84662. };
  84663. var internalTexture = rtt.getInternalTexture();
  84664. if (internalTexture) {
  84665. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84666. engine.unBindFramebuffer(internalTexture);
  84667. rtt.disposeFramebufferObjects();
  84668. passPostProcess.dispose();
  84669. internalTexture.isReady = true;
  84670. }
  84671. });
  84672. return rtt;
  84673. };
  84674. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84675. if (!scene._environmentBRDFTexture) {
  84676. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84677. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84678. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84679. scene._environmentBRDFTexture = texture;
  84680. }
  84681. return scene._environmentBRDFTexture;
  84682. };
  84683. 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=";
  84684. return TextureTools;
  84685. }());
  84686. BABYLON.TextureTools = TextureTools;
  84687. })(BABYLON || (BABYLON = {}));
  84688. //# sourceMappingURL=babylon.textureTools.js.map
  84689. var BABYLON;
  84690. (function (BABYLON) {
  84691. var FramingBehavior = /** @class */ (function () {
  84692. function FramingBehavior() {
  84693. this._mode = FramingBehavior.FitFrustumSidesMode;
  84694. this._radiusScale = 1.0;
  84695. this._positionScale = 0.5;
  84696. this._defaultElevation = 0.3;
  84697. this._elevationReturnTime = 1500;
  84698. this._elevationReturnWaitTime = 1000;
  84699. this._zoomStopsAnimation = false;
  84700. this._framingTime = 1500;
  84701. this._isPointerDown = false;
  84702. this._lastInteractionTime = -Infinity;
  84703. // Framing control
  84704. this._animatables = new Array();
  84705. this._betaIsAnimating = false;
  84706. }
  84707. Object.defineProperty(FramingBehavior.prototype, "name", {
  84708. get: function () {
  84709. return "Framing";
  84710. },
  84711. enumerable: true,
  84712. configurable: true
  84713. });
  84714. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84715. /**
  84716. * Gets current mode used by the behavior.
  84717. */
  84718. get: function () {
  84719. return this._mode;
  84720. },
  84721. /**
  84722. * Sets the current mode used by the behavior
  84723. */
  84724. set: function (mode) {
  84725. this._mode = mode;
  84726. },
  84727. enumerable: true,
  84728. configurable: true
  84729. });
  84730. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84731. /**
  84732. * Gets the scale applied to the radius
  84733. */
  84734. get: function () {
  84735. return this._radiusScale;
  84736. },
  84737. /**
  84738. * Sets the scale applied to the radius (1 by default)
  84739. */
  84740. set: function (radius) {
  84741. this._radiusScale = radius;
  84742. },
  84743. enumerable: true,
  84744. configurable: true
  84745. });
  84746. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  84747. /**
  84748. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84749. */
  84750. get: function () {
  84751. return this._positionScale;
  84752. },
  84753. /**
  84754. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84755. */
  84756. set: function (scale) {
  84757. this._positionScale = scale;
  84758. },
  84759. enumerable: true,
  84760. configurable: true
  84761. });
  84762. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  84763. /**
  84764. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84765. * behaviour is triggered, in radians.
  84766. */
  84767. get: function () {
  84768. return this._defaultElevation;
  84769. },
  84770. /**
  84771. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84772. * behaviour is triggered, in radians.
  84773. */
  84774. set: function (elevation) {
  84775. this._defaultElevation = elevation;
  84776. },
  84777. enumerable: true,
  84778. configurable: true
  84779. });
  84780. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  84781. /**
  84782. * Gets the time (in milliseconds) taken to return to the default beta position.
  84783. * Negative value indicates camera should not return to default.
  84784. */
  84785. get: function () {
  84786. return this._elevationReturnTime;
  84787. },
  84788. /**
  84789. * Sets the time (in milliseconds) taken to return to the default beta position.
  84790. * Negative value indicates camera should not return to default.
  84791. */
  84792. set: function (speed) {
  84793. this._elevationReturnTime = speed;
  84794. },
  84795. enumerable: true,
  84796. configurable: true
  84797. });
  84798. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  84799. /**
  84800. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84801. */
  84802. get: function () {
  84803. return this._elevationReturnWaitTime;
  84804. },
  84805. /**
  84806. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84807. */
  84808. set: function (time) {
  84809. this._elevationReturnWaitTime = time;
  84810. },
  84811. enumerable: true,
  84812. configurable: true
  84813. });
  84814. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  84815. /**
  84816. * Gets the flag that indicates if user zooming should stop animation.
  84817. */
  84818. get: function () {
  84819. return this._zoomStopsAnimation;
  84820. },
  84821. /**
  84822. * Sets the flag that indicates if user zooming should stop animation.
  84823. */
  84824. set: function (flag) {
  84825. this._zoomStopsAnimation = flag;
  84826. },
  84827. enumerable: true,
  84828. configurable: true
  84829. });
  84830. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  84831. /**
  84832. * Gets the transition time when framing the mesh, in milliseconds
  84833. */
  84834. get: function () {
  84835. return this._framingTime;
  84836. },
  84837. /**
  84838. * Sets the transition time when framing the mesh, in milliseconds
  84839. */
  84840. set: function (time) {
  84841. this._framingTime = time;
  84842. },
  84843. enumerable: true,
  84844. configurable: true
  84845. });
  84846. FramingBehavior.prototype.init = function () {
  84847. // Do notihng
  84848. };
  84849. FramingBehavior.prototype.attach = function (camera) {
  84850. var _this = this;
  84851. this._attachedCamera = camera;
  84852. var scene = this._attachedCamera.getScene();
  84853. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  84854. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84855. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84856. _this._isPointerDown = true;
  84857. return;
  84858. }
  84859. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84860. _this._isPointerDown = false;
  84861. }
  84862. });
  84863. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84864. if (mesh) {
  84865. _this.zoomOnMesh(mesh);
  84866. }
  84867. });
  84868. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84869. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84870. _this._applyUserInteraction();
  84871. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  84872. // back to the default position after a given timeout
  84873. _this._maintainCameraAboveGround();
  84874. });
  84875. };
  84876. FramingBehavior.prototype.detach = function () {
  84877. if (!this._attachedCamera) {
  84878. return;
  84879. }
  84880. var scene = this._attachedCamera.getScene();
  84881. if (this._onPrePointerObservableObserver) {
  84882. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  84883. }
  84884. if (this._onAfterCheckInputsObserver) {
  84885. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84886. }
  84887. if (this._onMeshTargetChangedObserver) {
  84888. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84889. }
  84890. this._attachedCamera = null;
  84891. };
  84892. /**
  84893. * Targets the given mesh and updates zoom level accordingly.
  84894. * @param mesh The mesh to target.
  84895. * @param radius Optional. If a cached radius position already exists, overrides default.
  84896. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84897. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84898. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84899. */
  84900. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  84901. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84902. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84903. mesh.computeWorldMatrix(true);
  84904. var boundingBox = mesh.getBoundingInfo().boundingBox;
  84905. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  84906. };
  84907. /**
  84908. * Targets the given mesh with its children and updates zoom level accordingly.
  84909. * @param mesh The mesh to target.
  84910. * @param radius Optional. If a cached radius position already exists, overrides default.
  84911. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84912. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84913. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84914. */
  84915. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  84916. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84917. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84918. mesh.computeWorldMatrix(true);
  84919. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  84920. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  84921. };
  84922. /**
  84923. * Targets the given meshes with their children and updates zoom level accordingly.
  84924. * @param meshes The mesh to target.
  84925. * @param radius Optional. If a cached radius position already exists, overrides default.
  84926. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84927. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84928. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84929. */
  84930. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  84931. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84932. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84933. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  84934. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  84935. for (var i = 0; i < meshes.length; i++) {
  84936. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  84937. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  84938. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  84939. }
  84940. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  84941. };
  84942. /**
  84943. * Targets the given mesh and updates zoom level accordingly.
  84944. * @param mesh The mesh to target.
  84945. * @param radius Optional. If a cached radius position already exists, overrides default.
  84946. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84947. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84948. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84949. */
  84950. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  84951. var _this = this;
  84952. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84953. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84954. var zoomTarget;
  84955. if (!this._attachedCamera) {
  84956. return;
  84957. }
  84958. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  84959. var bottom = minimumWorld.y;
  84960. var top = maximumWorld.y;
  84961. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  84962. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  84963. if (focusOnOriginXZ) {
  84964. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  84965. }
  84966. else {
  84967. var centerWorld = minimumWorld.add(radiusWorld);
  84968. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  84969. }
  84970. if (!this._vectorTransition) {
  84971. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  84972. }
  84973. this._betaIsAnimating = true;
  84974. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  84975. if (animatable) {
  84976. this._animatables.push(animatable);
  84977. }
  84978. // sets the radius and lower radius bounds
  84979. // Small delta ensures camera is not always at lower zoom limit.
  84980. var radius = 0;
  84981. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  84982. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  84983. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  84984. radius = position;
  84985. }
  84986. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  84987. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  84988. if (this._attachedCamera.lowerRadiusLimit === null) {
  84989. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  84990. }
  84991. }
  84992. // Set sensibilities
  84993. var extend = maximumWorld.subtract(minimumWorld).length();
  84994. this._attachedCamera.panningSensibility = 5000 / extend;
  84995. this._attachedCamera.wheelPrecision = 100 / radius;
  84996. // transition to new radius
  84997. if (!this._radiusTransition) {
  84998. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  84999. }
  85000. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85001. if (onAnimationEnd) {
  85002. onAnimationEnd();
  85003. }
  85004. if (_this._attachedCamera) {
  85005. _this._attachedCamera.storeState();
  85006. }
  85007. });
  85008. if (animatable) {
  85009. this._animatables.push(animatable);
  85010. }
  85011. };
  85012. /**
  85013. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85014. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85015. * frustum width.
  85016. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85017. * to fully enclose the mesh in the viewing frustum.
  85018. */
  85019. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85020. var size = maximumWorld.subtract(minimumWorld);
  85021. var boxVectorGlobalDiagonal = size.length();
  85022. var frustumSlope = this._getFrustumSlope();
  85023. // Formula for setting distance
  85024. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85025. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85026. // Horizon distance
  85027. var radius = radiusWithoutFraming * this._radiusScale;
  85028. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85029. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85030. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85031. var camera = this._attachedCamera;
  85032. if (!camera) {
  85033. return 0;
  85034. }
  85035. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85036. // Don't exceed the requested limit
  85037. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85038. }
  85039. // Don't exceed the upper radius limit
  85040. if (camera.upperRadiusLimit) {
  85041. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85042. }
  85043. return distance;
  85044. };
  85045. /**
  85046. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85047. * is automatically returned to its default position (expected to be above ground plane).
  85048. */
  85049. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85050. var _this = this;
  85051. if (this._elevationReturnTime < 0) {
  85052. return;
  85053. }
  85054. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85055. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85056. var limitBeta = Math.PI * 0.5;
  85057. // Bring the camera back up if below the ground plane
  85058. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85059. this._betaIsAnimating = true;
  85060. //Transition to new position
  85061. this.stopAllAnimations();
  85062. if (!this._betaTransition) {
  85063. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85064. }
  85065. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85066. _this._clearAnimationLocks();
  85067. _this.stopAllAnimations();
  85068. });
  85069. if (animatabe) {
  85070. this._animatables.push(animatabe);
  85071. }
  85072. }
  85073. };
  85074. /**
  85075. * Returns the frustum slope based on the canvas ratio and camera FOV
  85076. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85077. */
  85078. FramingBehavior.prototype._getFrustumSlope = function () {
  85079. // Calculate the viewport ratio
  85080. // Aspect Ratio is Height/Width.
  85081. var camera = this._attachedCamera;
  85082. if (!camera) {
  85083. return BABYLON.Vector2.Zero();
  85084. }
  85085. var engine = camera.getScene().getEngine();
  85086. var aspectRatio = engine.getAspectRatio(camera);
  85087. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85088. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85089. var frustumSlopeY = Math.tan(camera.fov / 2);
  85090. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85091. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85092. // along the forward vector.
  85093. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85094. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85095. };
  85096. /**
  85097. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85098. */
  85099. FramingBehavior.prototype._clearAnimationLocks = function () {
  85100. this._betaIsAnimating = false;
  85101. };
  85102. /**
  85103. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85104. */
  85105. FramingBehavior.prototype._applyUserInteraction = function () {
  85106. if (this.isUserIsMoving) {
  85107. this._lastInteractionTime = BABYLON.Tools.Now;
  85108. this.stopAllAnimations();
  85109. this._clearAnimationLocks();
  85110. }
  85111. };
  85112. /**
  85113. * Stops and removes all animations that have been applied to the camera
  85114. */
  85115. FramingBehavior.prototype.stopAllAnimations = function () {
  85116. if (this._attachedCamera) {
  85117. this._attachedCamera.animations = [];
  85118. }
  85119. while (this._animatables.length) {
  85120. if (this._animatables[0]) {
  85121. this._animatables[0].onAnimationEnd = null;
  85122. this._animatables[0].stop();
  85123. }
  85124. this._animatables.shift();
  85125. }
  85126. };
  85127. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85128. /**
  85129. * Gets a value indicating if the user is moving the camera
  85130. */
  85131. get: function () {
  85132. if (!this._attachedCamera) {
  85133. return false;
  85134. }
  85135. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85136. this._attachedCamera.inertialBetaOffset !== 0 ||
  85137. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85138. this._attachedCamera.inertialPanningX !== 0 ||
  85139. this._attachedCamera.inertialPanningY !== 0 ||
  85140. this._isPointerDown;
  85141. },
  85142. enumerable: true,
  85143. configurable: true
  85144. });
  85145. /**
  85146. * The easing function used by animations
  85147. */
  85148. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85149. /**
  85150. * The easing mode used by animations
  85151. */
  85152. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85153. // Statics
  85154. /**
  85155. * The camera can move all the way towards the mesh.
  85156. */
  85157. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85158. /**
  85159. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85160. */
  85161. FramingBehavior.FitFrustumSidesMode = 1;
  85162. return FramingBehavior;
  85163. }());
  85164. BABYLON.FramingBehavior = FramingBehavior;
  85165. })(BABYLON || (BABYLON = {}));
  85166. //# sourceMappingURL=babylon.framingBehavior.js.map
  85167. var BABYLON;
  85168. (function (BABYLON) {
  85169. /**
  85170. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85171. */
  85172. var BouncingBehavior = /** @class */ (function () {
  85173. function BouncingBehavior() {
  85174. /**
  85175. * The duration of the animation, in milliseconds
  85176. */
  85177. this.transitionDuration = 450;
  85178. /**
  85179. * Length of the distance animated by the transition when lower radius is reached
  85180. */
  85181. this.lowerRadiusTransitionRange = 2;
  85182. /**
  85183. * Length of the distance animated by the transition when upper radius is reached
  85184. */
  85185. this.upperRadiusTransitionRange = -2;
  85186. this._autoTransitionRange = false;
  85187. // Animations
  85188. this._radiusIsAnimating = false;
  85189. this._radiusBounceTransition = null;
  85190. this._animatables = new Array();
  85191. }
  85192. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85193. get: function () {
  85194. return "Bouncing";
  85195. },
  85196. enumerable: true,
  85197. configurable: true
  85198. });
  85199. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85200. /**
  85201. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85202. */
  85203. get: function () {
  85204. return this._autoTransitionRange;
  85205. },
  85206. /**
  85207. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85208. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85209. */
  85210. set: function (value) {
  85211. var _this = this;
  85212. if (this._autoTransitionRange === value) {
  85213. return;
  85214. }
  85215. this._autoTransitionRange = value;
  85216. var camera = this._attachedCamera;
  85217. if (!camera) {
  85218. return;
  85219. }
  85220. if (value) {
  85221. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85222. if (!mesh) {
  85223. return;
  85224. }
  85225. mesh.computeWorldMatrix(true);
  85226. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85227. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85228. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85229. });
  85230. }
  85231. else if (this._onMeshTargetChangedObserver) {
  85232. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85233. }
  85234. },
  85235. enumerable: true,
  85236. configurable: true
  85237. });
  85238. BouncingBehavior.prototype.init = function () {
  85239. // Do notihng
  85240. };
  85241. BouncingBehavior.prototype.attach = function (camera) {
  85242. var _this = this;
  85243. this._attachedCamera = camera;
  85244. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85245. if (!_this._attachedCamera) {
  85246. return;
  85247. }
  85248. // Add the bounce animation to the lower radius limit
  85249. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85250. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85251. }
  85252. // Add the bounce animation to the upper radius limit
  85253. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85254. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85255. }
  85256. });
  85257. };
  85258. BouncingBehavior.prototype.detach = function () {
  85259. if (!this._attachedCamera) {
  85260. return;
  85261. }
  85262. if (this._onAfterCheckInputsObserver) {
  85263. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85264. }
  85265. if (this._onMeshTargetChangedObserver) {
  85266. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85267. }
  85268. this._attachedCamera = null;
  85269. };
  85270. /**
  85271. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85272. * @param radiusLimit The limit to check against.
  85273. * @return Bool to indicate if at limit.
  85274. */
  85275. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85276. if (!this._attachedCamera) {
  85277. return false;
  85278. }
  85279. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85280. return true;
  85281. }
  85282. return false;
  85283. };
  85284. /**
  85285. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85286. * @param radiusDelta The delta by which to animate to. Can be negative.
  85287. */
  85288. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85289. var _this = this;
  85290. if (!this._attachedCamera) {
  85291. return;
  85292. }
  85293. if (!this._radiusBounceTransition) {
  85294. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85295. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85296. }
  85297. // Prevent zoom until bounce has completed
  85298. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85299. this._attachedCamera.wheelPrecision = Infinity;
  85300. this._attachedCamera.inertialRadiusOffset = 0;
  85301. // Animate to the radius limit
  85302. this.stopAllAnimations();
  85303. this._radiusIsAnimating = true;
  85304. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85305. if (animatable) {
  85306. this._animatables.push(animatable);
  85307. }
  85308. };
  85309. /**
  85310. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85311. */
  85312. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85313. this._radiusIsAnimating = false;
  85314. if (this._attachedCamera) {
  85315. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85316. }
  85317. };
  85318. /**
  85319. * Stops and removes all animations that have been applied to the camera
  85320. */
  85321. BouncingBehavior.prototype.stopAllAnimations = function () {
  85322. if (this._attachedCamera) {
  85323. this._attachedCamera.animations = [];
  85324. }
  85325. while (this._animatables.length) {
  85326. this._animatables[0].onAnimationEnd = null;
  85327. this._animatables[0].stop();
  85328. this._animatables.shift();
  85329. }
  85330. };
  85331. /**
  85332. * The easing function used by animations
  85333. */
  85334. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85335. /**
  85336. * The easing mode used by animations
  85337. */
  85338. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85339. return BouncingBehavior;
  85340. }());
  85341. BABYLON.BouncingBehavior = BouncingBehavior;
  85342. })(BABYLON || (BABYLON = {}));
  85343. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85344. var BABYLON;
  85345. (function (BABYLON) {
  85346. var AutoRotationBehavior = /** @class */ (function () {
  85347. function AutoRotationBehavior() {
  85348. this._zoomStopsAnimation = false;
  85349. this._idleRotationSpeed = 0.05;
  85350. this._idleRotationWaitTime = 2000;
  85351. this._idleRotationSpinupTime = 2000;
  85352. this._isPointerDown = false;
  85353. this._lastFrameTime = null;
  85354. this._lastInteractionTime = -Infinity;
  85355. this._cameraRotationSpeed = 0;
  85356. this._lastFrameRadius = 0;
  85357. }
  85358. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85359. get: function () {
  85360. return "AutoRotation";
  85361. },
  85362. enumerable: true,
  85363. configurable: true
  85364. });
  85365. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85366. /**
  85367. * Gets the flag that indicates if user zooming should stop animation.
  85368. */
  85369. get: function () {
  85370. return this._zoomStopsAnimation;
  85371. },
  85372. /**
  85373. * Sets the flag that indicates if user zooming should stop animation.
  85374. */
  85375. set: function (flag) {
  85376. this._zoomStopsAnimation = flag;
  85377. },
  85378. enumerable: true,
  85379. configurable: true
  85380. });
  85381. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85382. /**
  85383. * Gets the default speed at which the camera rotates around the model.
  85384. */
  85385. get: function () {
  85386. return this._idleRotationSpeed;
  85387. },
  85388. /**
  85389. * Sets the default speed at which the camera rotates around the model.
  85390. */
  85391. set: function (speed) {
  85392. this._idleRotationSpeed = speed;
  85393. },
  85394. enumerable: true,
  85395. configurable: true
  85396. });
  85397. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85398. /**
  85399. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85400. */
  85401. get: function () {
  85402. return this._idleRotationWaitTime;
  85403. },
  85404. /**
  85405. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85406. */
  85407. set: function (time) {
  85408. this._idleRotationWaitTime = time;
  85409. },
  85410. enumerable: true,
  85411. configurable: true
  85412. });
  85413. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85414. /**
  85415. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85416. */
  85417. get: function () {
  85418. return this._idleRotationSpinupTime;
  85419. },
  85420. /**
  85421. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85422. */
  85423. set: function (time) {
  85424. this._idleRotationSpinupTime = time;
  85425. },
  85426. enumerable: true,
  85427. configurable: true
  85428. });
  85429. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85430. /**
  85431. * Gets a value indicating if the camera is currently rotating because of this behavior
  85432. */
  85433. get: function () {
  85434. return Math.abs(this._cameraRotationSpeed) > 0;
  85435. },
  85436. enumerable: true,
  85437. configurable: true
  85438. });
  85439. AutoRotationBehavior.prototype.init = function () {
  85440. // Do notihng
  85441. };
  85442. AutoRotationBehavior.prototype.attach = function (camera) {
  85443. var _this = this;
  85444. this._attachedCamera = camera;
  85445. var scene = this._attachedCamera.getScene();
  85446. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85447. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85448. _this._isPointerDown = true;
  85449. return;
  85450. }
  85451. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85452. _this._isPointerDown = false;
  85453. }
  85454. });
  85455. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85456. var now = BABYLON.Tools.Now;
  85457. var dt = 0;
  85458. if (_this._lastFrameTime != null) {
  85459. dt = now - _this._lastFrameTime;
  85460. }
  85461. _this._lastFrameTime = now;
  85462. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85463. _this._applyUserInteraction();
  85464. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85465. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85466. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85467. // Step camera rotation by rotation speed
  85468. if (_this._attachedCamera) {
  85469. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85470. }
  85471. });
  85472. };
  85473. AutoRotationBehavior.prototype.detach = function () {
  85474. if (!this._attachedCamera) {
  85475. return;
  85476. }
  85477. var scene = this._attachedCamera.getScene();
  85478. if (this._onPrePointerObservableObserver) {
  85479. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85480. }
  85481. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85482. this._attachedCamera = null;
  85483. };
  85484. /**
  85485. * Returns true if user is scrolling.
  85486. * @return true if user is scrolling.
  85487. */
  85488. AutoRotationBehavior.prototype._userIsZooming = function () {
  85489. if (!this._attachedCamera) {
  85490. return false;
  85491. }
  85492. return this._attachedCamera.inertialRadiusOffset !== 0;
  85493. };
  85494. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85495. if (!this._attachedCamera) {
  85496. return false;
  85497. }
  85498. var zoomHasHitLimit = false;
  85499. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85500. zoomHasHitLimit = true;
  85501. }
  85502. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85503. this._lastFrameRadius = this._attachedCamera.radius;
  85504. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85505. };
  85506. /**
  85507. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85508. */
  85509. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85510. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85511. this._lastInteractionTime = BABYLON.Tools.Now;
  85512. }
  85513. };
  85514. // Tools
  85515. AutoRotationBehavior.prototype._userIsMoving = function () {
  85516. if (!this._attachedCamera) {
  85517. return false;
  85518. }
  85519. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85520. this._attachedCamera.inertialBetaOffset !== 0 ||
  85521. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85522. this._attachedCamera.inertialPanningX !== 0 ||
  85523. this._attachedCamera.inertialPanningY !== 0 ||
  85524. this._isPointerDown;
  85525. };
  85526. return AutoRotationBehavior;
  85527. }());
  85528. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85529. })(BABYLON || (BABYLON = {}));
  85530. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85531. var BABYLON;
  85532. (function (BABYLON) {
  85533. /**
  85534. * This class can be used to get instrumentation data from a Babylon engine
  85535. */
  85536. var EngineInstrumentation = /** @class */ (function () {
  85537. function EngineInstrumentation(engine) {
  85538. this.engine = engine;
  85539. this._captureGPUFrameTime = false;
  85540. this._gpuFrameTime = new BABYLON.PerfCounter();
  85541. this._captureShaderCompilationTime = false;
  85542. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85543. // Observers
  85544. this._onBeginFrameObserver = null;
  85545. this._onEndFrameObserver = null;
  85546. this._onBeforeShaderCompilationObserver = null;
  85547. this._onAfterShaderCompilationObserver = null;
  85548. }
  85549. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85550. // Properties
  85551. /**
  85552. * Gets the perf counter used for GPU frame time
  85553. */
  85554. get: function () {
  85555. return this._gpuFrameTime;
  85556. },
  85557. enumerable: true,
  85558. configurable: true
  85559. });
  85560. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85561. /**
  85562. * Gets the GPU frame time capture status
  85563. */
  85564. get: function () {
  85565. return this._captureGPUFrameTime;
  85566. },
  85567. /**
  85568. * Enable or disable the GPU frame time capture
  85569. */
  85570. set: function (value) {
  85571. var _this = this;
  85572. if (value === this._captureGPUFrameTime) {
  85573. return;
  85574. }
  85575. this._captureGPUFrameTime = value;
  85576. if (value) {
  85577. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85578. if (!_this._gpuFrameTimeToken) {
  85579. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85580. }
  85581. });
  85582. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85583. if (!_this._gpuFrameTimeToken) {
  85584. return;
  85585. }
  85586. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85587. if (time > -1) {
  85588. _this._gpuFrameTimeToken = null;
  85589. _this._gpuFrameTime.fetchNewFrame();
  85590. _this._gpuFrameTime.addCount(time, true);
  85591. }
  85592. });
  85593. }
  85594. else {
  85595. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85596. this._onBeginFrameObserver = null;
  85597. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85598. this._onEndFrameObserver = null;
  85599. }
  85600. },
  85601. enumerable: true,
  85602. configurable: true
  85603. });
  85604. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85605. /**
  85606. * Gets the perf counter used for shader compilation time
  85607. */
  85608. get: function () {
  85609. return this._shaderCompilationTime;
  85610. },
  85611. enumerable: true,
  85612. configurable: true
  85613. });
  85614. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85615. /**
  85616. * Gets the shader compilation time capture status
  85617. */
  85618. get: function () {
  85619. return this._captureShaderCompilationTime;
  85620. },
  85621. /**
  85622. * Enable or disable the shader compilation time capture
  85623. */
  85624. set: function (value) {
  85625. var _this = this;
  85626. if (value === this._captureShaderCompilationTime) {
  85627. return;
  85628. }
  85629. this._captureShaderCompilationTime = value;
  85630. if (value) {
  85631. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85632. _this._shaderCompilationTime.fetchNewFrame();
  85633. _this._shaderCompilationTime.beginMonitoring();
  85634. });
  85635. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85636. _this._shaderCompilationTime.endMonitoring();
  85637. });
  85638. }
  85639. else {
  85640. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85641. this._onBeforeShaderCompilationObserver = null;
  85642. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85643. this._onAfterShaderCompilationObserver = null;
  85644. }
  85645. },
  85646. enumerable: true,
  85647. configurable: true
  85648. });
  85649. EngineInstrumentation.prototype.dispose = function () {
  85650. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85651. this._onBeginFrameObserver = null;
  85652. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85653. this._onEndFrameObserver = null;
  85654. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85655. this._onBeforeShaderCompilationObserver = null;
  85656. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85657. this._onAfterShaderCompilationObserver = null;
  85658. this.engine = null;
  85659. };
  85660. return EngineInstrumentation;
  85661. }());
  85662. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85663. })(BABYLON || (BABYLON = {}));
  85664. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85665. var BABYLON;
  85666. (function (BABYLON) {
  85667. /**
  85668. * This class can be used to get instrumentation data from a Babylon engine
  85669. */
  85670. var SceneInstrumentation = /** @class */ (function () {
  85671. function SceneInstrumentation(scene) {
  85672. var _this = this;
  85673. this.scene = scene;
  85674. this._captureActiveMeshesEvaluationTime = false;
  85675. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85676. this._captureRenderTargetsRenderTime = false;
  85677. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85678. this._captureFrameTime = false;
  85679. this._frameTime = new BABYLON.PerfCounter();
  85680. this._captureRenderTime = false;
  85681. this._renderTime = new BABYLON.PerfCounter();
  85682. this._captureInterFrameTime = false;
  85683. this._interFrameTime = new BABYLON.PerfCounter();
  85684. this._captureParticlesRenderTime = false;
  85685. this._particlesRenderTime = new BABYLON.PerfCounter();
  85686. this._captureSpritesRenderTime = false;
  85687. this._spritesRenderTime = new BABYLON.PerfCounter();
  85688. this._capturePhysicsTime = false;
  85689. this._physicsTime = new BABYLON.PerfCounter();
  85690. this._captureAnimationsTime = false;
  85691. this._animationsTime = new BABYLON.PerfCounter();
  85692. // Observers
  85693. this._onBeforeActiveMeshesEvaluationObserver = null;
  85694. this._onAfterActiveMeshesEvaluationObserver = null;
  85695. this._onBeforeRenderTargetsRenderObserver = null;
  85696. this._onAfterRenderTargetsRenderObserver = null;
  85697. this._onAfterRenderObserver = null;
  85698. this._onBeforeDrawPhaseObserver = null;
  85699. this._onAfterDrawPhaseObserver = null;
  85700. this._onBeforeAnimationsObserver = null;
  85701. this._onBeforeParticlesRenderingObserver = null;
  85702. this._onAfterParticlesRenderingObserver = null;
  85703. this._onBeforeSpritesRenderingObserver = null;
  85704. this._onAfterSpritesRenderingObserver = null;
  85705. this._onBeforePhysicsObserver = null;
  85706. this._onAfterPhysicsObserver = null;
  85707. this._onAfterAnimationsObserver = null;
  85708. // Before render
  85709. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85710. if (_this._captureActiveMeshesEvaluationTime) {
  85711. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85712. }
  85713. if (_this._captureRenderTargetsRenderTime) {
  85714. _this._renderTargetsRenderTime.fetchNewFrame();
  85715. }
  85716. if (_this._captureFrameTime) {
  85717. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85718. _this._frameTime.beginMonitoring();
  85719. }
  85720. if (_this._captureInterFrameTime) {
  85721. _this._interFrameTime.endMonitoring();
  85722. }
  85723. if (_this._captureParticlesRenderTime) {
  85724. _this._particlesRenderTime.fetchNewFrame();
  85725. }
  85726. if (_this._captureSpritesRenderTime) {
  85727. _this._spritesRenderTime.fetchNewFrame();
  85728. }
  85729. if (_this._captureAnimationsTime) {
  85730. _this._animationsTime.beginMonitoring();
  85731. }
  85732. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85733. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85734. });
  85735. // After render
  85736. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85737. if (_this._captureFrameTime) {
  85738. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85739. _this._frameTime.endMonitoring();
  85740. }
  85741. if (_this._captureRenderTime) {
  85742. _this._renderTime.endMonitoring(false);
  85743. }
  85744. if (_this._captureInterFrameTime) {
  85745. _this._interFrameTime.beginMonitoring();
  85746. }
  85747. });
  85748. }
  85749. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  85750. // Properties
  85751. /**
  85752. * Gets the perf counter used for active meshes evaluation time
  85753. */
  85754. get: function () {
  85755. return this._activeMeshesEvaluationTime;
  85756. },
  85757. enumerable: true,
  85758. configurable: true
  85759. });
  85760. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  85761. /**
  85762. * Gets the active meshes evaluation time capture status
  85763. */
  85764. get: function () {
  85765. return this._captureActiveMeshesEvaluationTime;
  85766. },
  85767. /**
  85768. * Enable or disable the active meshes evaluation time capture
  85769. */
  85770. set: function (value) {
  85771. var _this = this;
  85772. if (value === this._captureActiveMeshesEvaluationTime) {
  85773. return;
  85774. }
  85775. this._captureActiveMeshesEvaluationTime = value;
  85776. if (value) {
  85777. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  85778. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  85779. _this._activeMeshesEvaluationTime.beginMonitoring();
  85780. });
  85781. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  85782. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  85783. _this._activeMeshesEvaluationTime.endMonitoring();
  85784. });
  85785. }
  85786. else {
  85787. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85788. this._onBeforeActiveMeshesEvaluationObserver = null;
  85789. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85790. this._onAfterActiveMeshesEvaluationObserver = null;
  85791. }
  85792. },
  85793. enumerable: true,
  85794. configurable: true
  85795. });
  85796. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  85797. /**
  85798. * Gets the perf counter used for render targets render time
  85799. */
  85800. get: function () {
  85801. return this._renderTargetsRenderTime;
  85802. },
  85803. enumerable: true,
  85804. configurable: true
  85805. });
  85806. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  85807. /**
  85808. * Gets the render targets render time capture status
  85809. */
  85810. get: function () {
  85811. return this._captureRenderTargetsRenderTime;
  85812. },
  85813. /**
  85814. * Enable or disable the render targets render time capture
  85815. */
  85816. set: function (value) {
  85817. var _this = this;
  85818. if (value === this._captureRenderTargetsRenderTime) {
  85819. return;
  85820. }
  85821. this._captureRenderTargetsRenderTime = value;
  85822. if (value) {
  85823. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  85824. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  85825. _this._renderTargetsRenderTime.beginMonitoring();
  85826. });
  85827. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  85828. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  85829. _this._renderTargetsRenderTime.endMonitoring(false);
  85830. });
  85831. }
  85832. else {
  85833. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85834. this._onBeforeRenderTargetsRenderObserver = null;
  85835. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85836. this._onAfterRenderTargetsRenderObserver = null;
  85837. }
  85838. },
  85839. enumerable: true,
  85840. configurable: true
  85841. });
  85842. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  85843. /**
  85844. * Gets the perf counter used for particles render time
  85845. */
  85846. get: function () {
  85847. return this._particlesRenderTime;
  85848. },
  85849. enumerable: true,
  85850. configurable: true
  85851. });
  85852. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  85853. /**
  85854. * Gets the particles render time capture status
  85855. */
  85856. get: function () {
  85857. return this._captureParticlesRenderTime;
  85858. },
  85859. /**
  85860. * Enable or disable the particles render time capture
  85861. */
  85862. set: function (value) {
  85863. var _this = this;
  85864. if (value === this._captureParticlesRenderTime) {
  85865. return;
  85866. }
  85867. this._captureParticlesRenderTime = value;
  85868. if (value) {
  85869. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  85870. BABYLON.Tools.StartPerformanceCounter("Particles");
  85871. _this._particlesRenderTime.beginMonitoring();
  85872. });
  85873. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  85874. BABYLON.Tools.EndPerformanceCounter("Particles");
  85875. _this._particlesRenderTime.endMonitoring(false);
  85876. });
  85877. }
  85878. else {
  85879. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  85880. this._onBeforeParticlesRenderingObserver = null;
  85881. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  85882. this._onAfterParticlesRenderingObserver = null;
  85883. }
  85884. },
  85885. enumerable: true,
  85886. configurable: true
  85887. });
  85888. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  85889. /**
  85890. * Gets the perf counter used for sprites render time
  85891. */
  85892. get: function () {
  85893. return this._spritesRenderTime;
  85894. },
  85895. enumerable: true,
  85896. configurable: true
  85897. });
  85898. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  85899. /**
  85900. * Gets the sprites render time capture status
  85901. */
  85902. get: function () {
  85903. return this._captureSpritesRenderTime;
  85904. },
  85905. /**
  85906. * Enable or disable the sprites render time capture
  85907. */
  85908. set: function (value) {
  85909. var _this = this;
  85910. if (value === this._captureSpritesRenderTime) {
  85911. return;
  85912. }
  85913. this._captureSpritesRenderTime = value;
  85914. if (value) {
  85915. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  85916. BABYLON.Tools.StartPerformanceCounter("Sprites");
  85917. _this._spritesRenderTime.beginMonitoring();
  85918. });
  85919. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  85920. BABYLON.Tools.EndPerformanceCounter("Sprites");
  85921. _this._spritesRenderTime.endMonitoring(false);
  85922. });
  85923. }
  85924. else {
  85925. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  85926. this._onBeforeSpritesRenderingObserver = null;
  85927. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  85928. this._onAfterSpritesRenderingObserver = null;
  85929. }
  85930. },
  85931. enumerable: true,
  85932. configurable: true
  85933. });
  85934. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  85935. /**
  85936. * Gets the perf counter used for physics time
  85937. */
  85938. get: function () {
  85939. return this._physicsTime;
  85940. },
  85941. enumerable: true,
  85942. configurable: true
  85943. });
  85944. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  85945. /**
  85946. * Gets the physics time capture status
  85947. */
  85948. get: function () {
  85949. return this._capturePhysicsTime;
  85950. },
  85951. /**
  85952. * Enable or disable the physics time capture
  85953. */
  85954. set: function (value) {
  85955. var _this = this;
  85956. if (value === this._capturePhysicsTime) {
  85957. return;
  85958. }
  85959. this._capturePhysicsTime = value;
  85960. if (value) {
  85961. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  85962. BABYLON.Tools.StartPerformanceCounter("Physics");
  85963. _this._physicsTime.beginMonitoring();
  85964. });
  85965. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  85966. BABYLON.Tools.EndPerformanceCounter("Physics");
  85967. _this._physicsTime.endMonitoring();
  85968. });
  85969. }
  85970. else {
  85971. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  85972. this._onBeforePhysicsObserver = null;
  85973. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  85974. this._onAfterPhysicsObserver = null;
  85975. }
  85976. },
  85977. enumerable: true,
  85978. configurable: true
  85979. });
  85980. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  85981. /**
  85982. * Gets the perf counter used for animations time
  85983. */
  85984. get: function () {
  85985. return this._animationsTime;
  85986. },
  85987. enumerable: true,
  85988. configurable: true
  85989. });
  85990. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  85991. /**
  85992. * Gets the animations time capture status
  85993. */
  85994. get: function () {
  85995. return this._captureAnimationsTime;
  85996. },
  85997. /**
  85998. * Enable or disable the animations time capture
  85999. */
  86000. set: function (value) {
  86001. var _this = this;
  86002. if (value === this._captureAnimationsTime) {
  86003. return;
  86004. }
  86005. this._captureAnimationsTime = value;
  86006. if (value) {
  86007. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86008. _this._animationsTime.endMonitoring();
  86009. });
  86010. }
  86011. else {
  86012. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86013. this._onAfterAnimationsObserver = null;
  86014. }
  86015. },
  86016. enumerable: true,
  86017. configurable: true
  86018. });
  86019. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86020. /**
  86021. * Gets the perf counter used for frame time capture
  86022. */
  86023. get: function () {
  86024. return this._frameTime;
  86025. },
  86026. enumerable: true,
  86027. configurable: true
  86028. });
  86029. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86030. /**
  86031. * Gets the frame time capture status
  86032. */
  86033. get: function () {
  86034. return this._captureFrameTime;
  86035. },
  86036. /**
  86037. * Enable or disable the frame time capture
  86038. */
  86039. set: function (value) {
  86040. this._captureFrameTime = value;
  86041. },
  86042. enumerable: true,
  86043. configurable: true
  86044. });
  86045. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86046. /**
  86047. * Gets the perf counter used for inter-frames time capture
  86048. */
  86049. get: function () {
  86050. return this._interFrameTime;
  86051. },
  86052. enumerable: true,
  86053. configurable: true
  86054. });
  86055. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86056. /**
  86057. * Gets the inter-frames time capture status
  86058. */
  86059. get: function () {
  86060. return this._captureInterFrameTime;
  86061. },
  86062. /**
  86063. * Enable or disable the inter-frames time capture
  86064. */
  86065. set: function (value) {
  86066. this._captureInterFrameTime = value;
  86067. },
  86068. enumerable: true,
  86069. configurable: true
  86070. });
  86071. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86072. /**
  86073. * Gets the perf counter used for render time capture
  86074. */
  86075. get: function () {
  86076. return this._renderTime;
  86077. },
  86078. enumerable: true,
  86079. configurable: true
  86080. });
  86081. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86082. /**
  86083. * Gets the render time capture status
  86084. */
  86085. get: function () {
  86086. return this._captureRenderTime;
  86087. },
  86088. /**
  86089. * Enable or disable the render time capture
  86090. */
  86091. set: function (value) {
  86092. var _this = this;
  86093. if (value === this._captureRenderTime) {
  86094. return;
  86095. }
  86096. this._captureRenderTime = value;
  86097. if (value) {
  86098. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86099. _this._renderTime.beginMonitoring();
  86100. BABYLON.Tools.StartPerformanceCounter("Main render");
  86101. });
  86102. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86103. _this._renderTime.endMonitoring(false);
  86104. BABYLON.Tools.EndPerformanceCounter("Main render");
  86105. });
  86106. }
  86107. else {
  86108. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86109. this._onBeforeDrawPhaseObserver = null;
  86110. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86111. this._onAfterDrawPhaseObserver = null;
  86112. }
  86113. },
  86114. enumerable: true,
  86115. configurable: true
  86116. });
  86117. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86118. /**
  86119. * Gets the perf counter used for draw calls
  86120. */
  86121. get: function () {
  86122. return this.scene.getEngine()._drawCalls;
  86123. },
  86124. enumerable: true,
  86125. configurable: true
  86126. });
  86127. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86128. /**
  86129. * Gets the perf counter used for texture collisions
  86130. */
  86131. get: function () {
  86132. return this.scene.getEngine()._textureCollisions;
  86133. },
  86134. enumerable: true,
  86135. configurable: true
  86136. });
  86137. SceneInstrumentation.prototype.dispose = function () {
  86138. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86139. this._onAfterRenderObserver = null;
  86140. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86141. this._onBeforeActiveMeshesEvaluationObserver = null;
  86142. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86143. this._onAfterActiveMeshesEvaluationObserver = null;
  86144. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86145. this._onBeforeRenderTargetsRenderObserver = null;
  86146. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86147. this._onAfterRenderTargetsRenderObserver = null;
  86148. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86149. this._onBeforeAnimationsObserver = null;
  86150. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86151. this._onBeforeParticlesRenderingObserver = null;
  86152. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86153. this._onAfterParticlesRenderingObserver = null;
  86154. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86155. this._onBeforeSpritesRenderingObserver = null;
  86156. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86157. this._onAfterSpritesRenderingObserver = null;
  86158. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86159. this._onBeforeDrawPhaseObserver = null;
  86160. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86161. this._onAfterDrawPhaseObserver = null;
  86162. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86163. this._onBeforePhysicsObserver = null;
  86164. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86165. this._onAfterPhysicsObserver = null;
  86166. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86167. this._onAfterAnimationsObserver = null;
  86168. this.scene = null;
  86169. };
  86170. return SceneInstrumentation;
  86171. }());
  86172. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86173. })(BABYLON || (BABYLON = {}));
  86174. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86175. var BABYLON;
  86176. (function (BABYLON) {
  86177. var _TimeToken = /** @class */ (function () {
  86178. function _TimeToken() {
  86179. this._timeElapsedQueryEnded = false;
  86180. }
  86181. return _TimeToken;
  86182. }());
  86183. BABYLON._TimeToken = _TimeToken;
  86184. })(BABYLON || (BABYLON = {}));
  86185. //# sourceMappingURL=babylon.timeToken.js.map
  86186. var BABYLON;
  86187. (function (BABYLON) {
  86188. /**
  86189. * Background material defines definition.
  86190. * @ignore Mainly internal Use
  86191. */
  86192. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86193. __extends(BackgroundMaterialDefines, _super);
  86194. /**
  86195. * Constructor of the defines.
  86196. */
  86197. function BackgroundMaterialDefines() {
  86198. var _this = _super.call(this) || this;
  86199. /**
  86200. * True if the diffuse texture is in use.
  86201. */
  86202. _this.DIFFUSE = false;
  86203. /**
  86204. * The direct UV channel to use.
  86205. */
  86206. _this.DIFFUSEDIRECTUV = 0;
  86207. /**
  86208. * True if the diffuse texture is in gamma space.
  86209. */
  86210. _this.GAMMADIFFUSE = false;
  86211. /**
  86212. * True if the diffuse texture has opacity in the alpha channel.
  86213. */
  86214. _this.DIFFUSEHASALPHA = false;
  86215. /**
  86216. * True if you want the material to fade to transparent at grazing angle.
  86217. */
  86218. _this.OPACITYFRESNEL = false;
  86219. /**
  86220. * True if an extra blur needs to be added in the reflection.
  86221. */
  86222. _this.REFLECTIONBLUR = false;
  86223. /**
  86224. * True if you want the material to fade to reflection at grazing angle.
  86225. */
  86226. _this.REFLECTIONFRESNEL = false;
  86227. /**
  86228. * True if you want the material to falloff as far as you move away from the scene center.
  86229. */
  86230. _this.REFLECTIONFALLOFF = false;
  86231. /**
  86232. * False if the current Webgl implementation does not support the texture lod extension.
  86233. */
  86234. _this.TEXTURELODSUPPORT = false;
  86235. /**
  86236. * True to ensure the data are premultiplied.
  86237. */
  86238. _this.PREMULTIPLYALPHA = false;
  86239. /**
  86240. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86241. */
  86242. _this.USERGBCOLOR = false;
  86243. /**
  86244. * True to add noise in order to reduce the banding effect.
  86245. */
  86246. _this.NOISE = false;
  86247. // Image Processing Configuration.
  86248. _this.IMAGEPROCESSING = false;
  86249. _this.VIGNETTE = false;
  86250. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86251. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86252. _this.TONEMAPPING = false;
  86253. _this.CONTRAST = false;
  86254. _this.COLORCURVES = false;
  86255. _this.COLORGRADING = false;
  86256. _this.COLORGRADING3D = false;
  86257. _this.SAMPLER3DGREENDEPTH = false;
  86258. _this.SAMPLER3DBGRMAP = false;
  86259. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86260. _this.EXPOSURE = false;
  86261. // Reflection.
  86262. _this.REFLECTION = false;
  86263. _this.REFLECTIONMAP_3D = false;
  86264. _this.REFLECTIONMAP_SPHERICAL = false;
  86265. _this.REFLECTIONMAP_PLANAR = false;
  86266. _this.REFLECTIONMAP_CUBIC = false;
  86267. _this.REFLECTIONMAP_PROJECTION = false;
  86268. _this.REFLECTIONMAP_SKYBOX = false;
  86269. _this.REFLECTIONMAP_EXPLICIT = false;
  86270. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86271. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86272. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86273. _this.INVERTCUBICMAP = false;
  86274. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86275. _this.LODINREFLECTIONALPHA = false;
  86276. _this.GAMMAREFLECTION = false;
  86277. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86278. // Default BJS.
  86279. _this.MAINUV1 = false;
  86280. _this.MAINUV2 = false;
  86281. _this.UV1 = false;
  86282. _this.UV2 = false;
  86283. _this.CLIPPLANE = false;
  86284. _this.POINTSIZE = false;
  86285. _this.FOG = false;
  86286. _this.NORMAL = false;
  86287. _this.NUM_BONE_INFLUENCERS = 0;
  86288. _this.BonesPerMesh = 0;
  86289. _this.INSTANCES = false;
  86290. _this.SHADOWFLOAT = false;
  86291. _this.rebuild();
  86292. return _this;
  86293. }
  86294. return BackgroundMaterialDefines;
  86295. }(BABYLON.MaterialDefines));
  86296. /**
  86297. * Background material used to create an efficient environement around your scene.
  86298. */
  86299. var BackgroundMaterial = /** @class */ (function (_super) {
  86300. __extends(BackgroundMaterial, _super);
  86301. /**
  86302. * Instantiates a Background Material in the given scene
  86303. * @param name The friendly name of the material
  86304. * @param scene The scene to add the material to
  86305. */
  86306. function BackgroundMaterial(name, scene) {
  86307. var _this = _super.call(this, name, scene) || this;
  86308. /**
  86309. * Key light Color (multiply against the R channel of the environement texture)
  86310. */
  86311. _this.primaryColor = BABYLON.Color3.White();
  86312. /**
  86313. * Key light Level (allowing HDR output of the background)
  86314. */
  86315. _this.primaryLevel = 1;
  86316. /**
  86317. * Secondary light Color (multiply against the G channel of the environement texture)
  86318. */
  86319. _this.secondaryColor = BABYLON.Color3.Gray();
  86320. /**
  86321. * Secondary light Level (allowing HDR output of the background)
  86322. */
  86323. _this.secondaryLevel = 1;
  86324. /**
  86325. * Tertiary light Color (multiply against the B channel of the environement texture)
  86326. */
  86327. _this.tertiaryColor = BABYLON.Color3.Black();
  86328. /**
  86329. * Tertiary light Level (allowing HDR output of the background)
  86330. */
  86331. _this.tertiaryLevel = 1;
  86332. /**
  86333. * Reflection Texture used in the material.
  86334. * Should be author in a specific way for the best result (refer to the documentation).
  86335. */
  86336. _this.reflectionTexture = null;
  86337. /**
  86338. * Reflection Texture level of blur.
  86339. *
  86340. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86341. * texture twice.
  86342. */
  86343. _this.reflectionBlur = 0;
  86344. /**
  86345. * Diffuse Texture used in the material.
  86346. * Should be author in a specific way for the best result (refer to the documentation).
  86347. */
  86348. _this.diffuseTexture = null;
  86349. _this._shadowLights = null;
  86350. /**
  86351. * Specify the list of lights casting shadow on the material.
  86352. * All scene shadow lights will be included if null.
  86353. */
  86354. _this.shadowLights = null;
  86355. /**
  86356. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86357. * soft lighting on the background.
  86358. */
  86359. _this.shadowBlurScale = 1;
  86360. /**
  86361. * Helps adjusting the shadow to a softer level if required.
  86362. * 0 means black shadows and 1 means no shadows.
  86363. */
  86364. _this.shadowLevel = 0;
  86365. /**
  86366. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86367. * It is usually zero but might be interesting to modify according to your setup.
  86368. */
  86369. _this.sceneCenter = BABYLON.Vector3.Zero();
  86370. /**
  86371. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86372. * This helps ensuring a nice transition when the camera goes under the ground.
  86373. */
  86374. _this.opacityFresnel = true;
  86375. /**
  86376. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86377. * This helps adding a mirror texture on the ground.
  86378. */
  86379. _this.reflectionFresnel = false;
  86380. /**
  86381. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86382. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86383. */
  86384. _this.reflectionFalloffDistance = 0.0;
  86385. /**
  86386. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86387. */
  86388. _this.reflectionAmount = 1.0;
  86389. /**
  86390. * This specifies the weight of the reflection at grazing angle.
  86391. */
  86392. _this.reflectionReflectance0 = 0.05;
  86393. /**
  86394. * This specifies the weight of the reflection at a perpendicular point of view.
  86395. */
  86396. _this.reflectionReflectance90 = 0.5;
  86397. /**
  86398. * Helps to directly use the maps channels instead of their level.
  86399. */
  86400. _this.useRGBColor = true;
  86401. /**
  86402. * This helps reducing the banding effect that could occur on the background.
  86403. */
  86404. _this.enableNoise = false;
  86405. _this._fovMultiplier = 1.0;
  86406. /**
  86407. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86408. * @type {boolean}
  86409. */
  86410. _this.useEquirectangularFOV = false;
  86411. _this._maxSimultaneousLights = 4;
  86412. /**
  86413. * Number of Simultaneous lights allowed on the material.
  86414. */
  86415. _this.maxSimultaneousLights = 4;
  86416. /**
  86417. * Keep track of the image processing observer to allow dispose and replace.
  86418. */
  86419. _this._imageProcessingObserver = null;
  86420. // Temp values kept as cache in the material.
  86421. _this._renderTargets = new BABYLON.SmartArray(16);
  86422. _this._reflectionControls = BABYLON.Vector4.Zero();
  86423. // Setup the default processing configuration to the scene.
  86424. _this._attachImageProcessingConfiguration(null);
  86425. _this.getRenderTargetTextures = function () {
  86426. _this._renderTargets.reset();
  86427. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86428. _this._renderTargets.push(_this._diffuseTexture);
  86429. }
  86430. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86431. _this._renderTargets.push(_this._reflectionTexture);
  86432. }
  86433. return _this._renderTargets;
  86434. };
  86435. return _this;
  86436. }
  86437. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86438. /**
  86439. * Sets the reflection reflectance fresnel values according to the default standard
  86440. * empirically know to work well :-)
  86441. */
  86442. set: function (value) {
  86443. var reflectionWeight = value;
  86444. if (reflectionWeight < 0.5) {
  86445. reflectionWeight = reflectionWeight * 2.0;
  86446. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86447. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86448. }
  86449. else {
  86450. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86451. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86452. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86453. }
  86454. },
  86455. enumerable: true,
  86456. configurable: true
  86457. });
  86458. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86459. /**
  86460. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86461. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86462. * Recommended to be keep at 1.0 except for special cases.
  86463. */
  86464. get: function () {
  86465. return this._fovMultiplier;
  86466. },
  86467. set: function (value) {
  86468. if (isNaN(value)) {
  86469. value = 1.0;
  86470. }
  86471. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86472. },
  86473. enumerable: true,
  86474. configurable: true
  86475. });
  86476. /**
  86477. * Attaches a new image processing configuration to the PBR Material.
  86478. * @param configuration (if null the scene configuration will be use)
  86479. */
  86480. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86481. var _this = this;
  86482. if (configuration === this._imageProcessingConfiguration) {
  86483. return;
  86484. }
  86485. // Detaches observer.
  86486. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86487. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86488. }
  86489. // Pick the scene configuration if needed.
  86490. if (!configuration) {
  86491. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86492. }
  86493. else {
  86494. this._imageProcessingConfiguration = configuration;
  86495. }
  86496. // Attaches observer.
  86497. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86498. _this._markAllSubMeshesAsImageProcessingDirty();
  86499. });
  86500. };
  86501. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86502. /**
  86503. * Gets the image processing configuration used either in this material.
  86504. */
  86505. get: function () {
  86506. return this._imageProcessingConfiguration;
  86507. },
  86508. /**
  86509. * Sets the Default image processing configuration used either in the this material.
  86510. *
  86511. * If sets to null, the scene one is in use.
  86512. */
  86513. set: function (value) {
  86514. this._attachImageProcessingConfiguration(value);
  86515. // Ensure the effect will be rebuilt.
  86516. this._markAllSubMeshesAsTexturesDirty();
  86517. },
  86518. enumerable: true,
  86519. configurable: true
  86520. });
  86521. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86522. /**
  86523. * Gets wether the color curves effect is enabled.
  86524. */
  86525. get: function () {
  86526. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86527. },
  86528. /**
  86529. * Sets wether the color curves effect is enabled.
  86530. */
  86531. set: function (value) {
  86532. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86533. },
  86534. enumerable: true,
  86535. configurable: true
  86536. });
  86537. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86538. /**
  86539. * Gets wether the color grading effect is enabled.
  86540. */
  86541. get: function () {
  86542. return this.imageProcessingConfiguration.colorGradingEnabled;
  86543. },
  86544. /**
  86545. * Gets wether the color grading effect is enabled.
  86546. */
  86547. set: function (value) {
  86548. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86549. },
  86550. enumerable: true,
  86551. configurable: true
  86552. });
  86553. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86554. /**
  86555. * Gets wether tonemapping is enabled or not.
  86556. */
  86557. get: function () {
  86558. return this._imageProcessingConfiguration.toneMappingEnabled;
  86559. },
  86560. /**
  86561. * Sets wether tonemapping is enabled or not
  86562. */
  86563. set: function (value) {
  86564. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86565. },
  86566. enumerable: true,
  86567. configurable: true
  86568. });
  86569. ;
  86570. ;
  86571. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86572. /**
  86573. * The camera exposure used on this material.
  86574. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86575. * This corresponds to a photographic exposure.
  86576. */
  86577. get: function () {
  86578. return this._imageProcessingConfiguration.exposure;
  86579. },
  86580. /**
  86581. * The camera exposure used on this material.
  86582. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86583. * This corresponds to a photographic exposure.
  86584. */
  86585. set: function (value) {
  86586. this._imageProcessingConfiguration.exposure = value;
  86587. },
  86588. enumerable: true,
  86589. configurable: true
  86590. });
  86591. ;
  86592. ;
  86593. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86594. /**
  86595. * Gets The camera contrast used on this material.
  86596. */
  86597. get: function () {
  86598. return this._imageProcessingConfiguration.contrast;
  86599. },
  86600. /**
  86601. * Sets The camera contrast used on this material.
  86602. */
  86603. set: function (value) {
  86604. this._imageProcessingConfiguration.contrast = value;
  86605. },
  86606. enumerable: true,
  86607. configurable: true
  86608. });
  86609. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86610. /**
  86611. * Gets the Color Grading 2D Lookup Texture.
  86612. */
  86613. get: function () {
  86614. return this._imageProcessingConfiguration.colorGradingTexture;
  86615. },
  86616. /**
  86617. * Sets the Color Grading 2D Lookup Texture.
  86618. */
  86619. set: function (value) {
  86620. this.imageProcessingConfiguration.colorGradingTexture = value;
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86626. /**
  86627. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86628. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86629. * 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;
  86630. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86631. */
  86632. get: function () {
  86633. return this.imageProcessingConfiguration.colorCurves;
  86634. },
  86635. /**
  86636. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86637. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86638. * 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;
  86639. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86640. */
  86641. set: function (value) {
  86642. this.imageProcessingConfiguration.colorCurves = value;
  86643. },
  86644. enumerable: true,
  86645. configurable: true
  86646. });
  86647. /**
  86648. * The entire material has been created in order to prevent overdraw.
  86649. * @returns false
  86650. */
  86651. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86652. return true;
  86653. };
  86654. /**
  86655. * The entire material has been created in order to prevent overdraw.
  86656. * @returns true if blending is enable
  86657. */
  86658. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86659. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86660. };
  86661. /**
  86662. * Checks wether the material is ready to be rendered for a given mesh.
  86663. * @param mesh The mesh to render
  86664. * @param subMesh The submesh to check against
  86665. * @param useInstances Specify wether or not the material is used with instances
  86666. * @returns true if all the dependencies are ready (Textures, Effects...)
  86667. */
  86668. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86669. var _this = this;
  86670. if (useInstances === void 0) { useInstances = false; }
  86671. if (subMesh.effect && this.isFrozen) {
  86672. if (this._wasPreviouslyReady) {
  86673. return true;
  86674. }
  86675. }
  86676. if (!subMesh._materialDefines) {
  86677. subMesh._materialDefines = new BackgroundMaterialDefines();
  86678. }
  86679. var scene = this.getScene();
  86680. var defines = subMesh._materialDefines;
  86681. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86682. if (defines._renderId === scene.getRenderId()) {
  86683. return true;
  86684. }
  86685. }
  86686. var engine = scene.getEngine();
  86687. // Lights
  86688. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86689. defines._needNormals = true;
  86690. // Textures
  86691. if (defines._areTexturesDirty) {
  86692. defines._needUVs = false;
  86693. if (scene.texturesEnabled) {
  86694. if (scene.getEngine().getCaps().textureLOD) {
  86695. defines.TEXTURELODSUPPORT = true;
  86696. }
  86697. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86698. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86699. return false;
  86700. }
  86701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86702. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86703. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86704. defines.OPACITYFRESNEL = this._opacityFresnel;
  86705. }
  86706. else {
  86707. defines.DIFFUSE = false;
  86708. defines.DIFFUSEHASALPHA = false;
  86709. defines.GAMMADIFFUSE = false;
  86710. defines.OPACITYFRESNEL = false;
  86711. }
  86712. var reflectionTexture = this._reflectionTexture;
  86713. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86714. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86715. return false;
  86716. }
  86717. defines.REFLECTION = true;
  86718. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86719. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86720. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86721. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86722. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86723. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86724. defines.INVERTCUBICMAP = true;
  86725. }
  86726. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86727. switch (reflectionTexture.coordinatesMode) {
  86728. case BABYLON.Texture.CUBIC_MODE:
  86729. case BABYLON.Texture.INVCUBIC_MODE:
  86730. defines.REFLECTIONMAP_CUBIC = true;
  86731. break;
  86732. case BABYLON.Texture.EXPLICIT_MODE:
  86733. defines.REFLECTIONMAP_EXPLICIT = true;
  86734. break;
  86735. case BABYLON.Texture.PLANAR_MODE:
  86736. defines.REFLECTIONMAP_PLANAR = true;
  86737. break;
  86738. case BABYLON.Texture.PROJECTION_MODE:
  86739. defines.REFLECTIONMAP_PROJECTION = true;
  86740. break;
  86741. case BABYLON.Texture.SKYBOX_MODE:
  86742. defines.REFLECTIONMAP_SKYBOX = true;
  86743. break;
  86744. case BABYLON.Texture.SPHERICAL_MODE:
  86745. defines.REFLECTIONMAP_SPHERICAL = true;
  86746. break;
  86747. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  86748. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  86749. break;
  86750. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  86751. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  86752. break;
  86753. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  86754. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  86755. break;
  86756. }
  86757. if (this.reflectionFresnel) {
  86758. defines.REFLECTIONFRESNEL = true;
  86759. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  86760. this._reflectionControls.x = this.reflectionAmount;
  86761. this._reflectionControls.y = this.reflectionReflectance0;
  86762. this._reflectionControls.z = this.reflectionReflectance90;
  86763. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  86764. }
  86765. else {
  86766. defines.REFLECTIONFRESNEL = false;
  86767. defines.REFLECTIONFALLOFF = false;
  86768. }
  86769. }
  86770. else {
  86771. defines.REFLECTION = false;
  86772. defines.REFLECTIONFALLOFF = false;
  86773. defines.REFLECTIONBLUR = false;
  86774. defines.REFLECTIONMAP_3D = false;
  86775. defines.REFLECTIONMAP_SPHERICAL = false;
  86776. defines.REFLECTIONMAP_PLANAR = false;
  86777. defines.REFLECTIONMAP_CUBIC = false;
  86778. defines.REFLECTIONMAP_PROJECTION = false;
  86779. defines.REFLECTIONMAP_SKYBOX = false;
  86780. defines.REFLECTIONMAP_EXPLICIT = false;
  86781. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86782. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86783. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86784. defines.INVERTCUBICMAP = false;
  86785. defines.REFLECTIONMAP_OPPOSITEZ = false;
  86786. defines.LODINREFLECTIONALPHA = false;
  86787. defines.GAMMAREFLECTION = false;
  86788. }
  86789. }
  86790. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  86791. defines.USERGBCOLOR = this._useRGBColor;
  86792. defines.NOISE = this._enableNoise;
  86793. }
  86794. if (defines._areImageProcessingDirty) {
  86795. if (!this._imageProcessingConfiguration.isReady()) {
  86796. return false;
  86797. }
  86798. this._imageProcessingConfiguration.prepareDefines(defines);
  86799. }
  86800. // Misc.
  86801. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  86802. // Values that need to be evaluated on every frame
  86803. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  86804. // Attribs
  86805. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  86806. if (mesh) {
  86807. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86808. mesh.createNormals(true);
  86809. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  86810. }
  86811. }
  86812. }
  86813. // Get correct effect
  86814. if (defines.isDirty) {
  86815. defines.markAsProcessed();
  86816. scene.resetCachedMaterial();
  86817. // Fallbacks
  86818. var fallbacks = new BABYLON.EffectFallbacks();
  86819. if (defines.FOG) {
  86820. fallbacks.addFallback(0, "FOG");
  86821. }
  86822. if (defines.POINTSIZE) {
  86823. fallbacks.addFallback(1, "POINTSIZE");
  86824. }
  86825. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  86826. if (defines.NUM_BONE_INFLUENCERS > 0) {
  86827. fallbacks.addCPUSkinningFallback(0, mesh);
  86828. }
  86829. //Attributes
  86830. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86831. if (defines.NORMAL) {
  86832. attribs.push(BABYLON.VertexBuffer.NormalKind);
  86833. }
  86834. if (defines.UV1) {
  86835. attribs.push(BABYLON.VertexBuffer.UVKind);
  86836. }
  86837. if (defines.UV2) {
  86838. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86839. }
  86840. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  86841. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  86842. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  86843. "vFogInfos", "vFogColor", "pointSize",
  86844. "vClipPlane", "mBones",
  86845. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  86846. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  86847. "shadowLevel", "alpha",
  86848. "vBackgroundCenter", "vReflectionControl",
  86849. "vDiffuseInfos", "diffuseMatrix",
  86850. ];
  86851. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  86852. var uniformBuffers = ["Material", "Scene"];
  86853. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  86854. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  86855. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  86856. uniformsNames: uniforms,
  86857. uniformBuffersNames: uniformBuffers,
  86858. samplers: samplers,
  86859. defines: defines,
  86860. maxSimultaneousLights: this._maxSimultaneousLights
  86861. });
  86862. var onCompiled = function (effect) {
  86863. if (_this.onCompiled) {
  86864. _this.onCompiled(effect);
  86865. }
  86866. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  86867. };
  86868. var join = defines.toString();
  86869. subMesh.setEffect(scene.getEngine().createEffect("background", {
  86870. attributes: attribs,
  86871. uniformsNames: uniforms,
  86872. uniformBuffersNames: uniformBuffers,
  86873. samplers: samplers,
  86874. defines: join,
  86875. fallbacks: fallbacks,
  86876. onCompiled: onCompiled,
  86877. onError: this.onError,
  86878. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  86879. }, engine), defines);
  86880. this.buildUniformLayout();
  86881. }
  86882. if (!subMesh.effect || !subMesh.effect.isReady()) {
  86883. return false;
  86884. }
  86885. defines._renderId = scene.getRenderId();
  86886. this._wasPreviouslyReady = true;
  86887. return true;
  86888. };
  86889. /**
  86890. * Build the uniform buffer used in the material.
  86891. */
  86892. BackgroundMaterial.prototype.buildUniformLayout = function () {
  86893. // Order is important !
  86894. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  86895. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  86896. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  86897. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  86898. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  86899. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  86900. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  86901. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  86902. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  86903. this._uniformBuffer.addUniform("pointSize", 1);
  86904. this._uniformBuffer.addUniform("shadowLevel", 1);
  86905. this._uniformBuffer.addUniform("alpha", 1);
  86906. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  86907. this._uniformBuffer.addUniform("vReflectionControl", 4);
  86908. this._uniformBuffer.create();
  86909. };
  86910. /**
  86911. * Unbind the material.
  86912. */
  86913. BackgroundMaterial.prototype.unbind = function () {
  86914. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  86915. this._uniformBuffer.setTexture("diffuseSampler", null);
  86916. }
  86917. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  86918. this._uniformBuffer.setTexture("reflectionSampler", null);
  86919. }
  86920. _super.prototype.unbind.call(this);
  86921. };
  86922. /**
  86923. * Bind only the world matrix to the material.
  86924. * @param world The world matrix to bind.
  86925. */
  86926. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  86927. this._activeEffect.setMatrix("world", world);
  86928. };
  86929. /**
  86930. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  86931. * @param world The world matrix to bind.
  86932. * @param subMesh The submesh to bind for.
  86933. */
  86934. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  86935. var scene = this.getScene();
  86936. var defines = subMesh._materialDefines;
  86937. if (!defines) {
  86938. return;
  86939. }
  86940. var effect = subMesh.effect;
  86941. if (!effect) {
  86942. return;
  86943. }
  86944. this._activeEffect = effect;
  86945. // Matrices
  86946. this.bindOnlyWorldMatrix(world);
  86947. // Bones
  86948. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  86949. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  86950. if (mustRebind) {
  86951. this._uniformBuffer.bindToEffect(effect, "Material");
  86952. this.bindViewProjection(effect);
  86953. var reflectionTexture = this._reflectionTexture;
  86954. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  86955. // Texture uniforms
  86956. if (scene.texturesEnabled) {
  86957. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86958. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  86959. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  86960. }
  86961. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86962. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  86963. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  86964. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  86965. }
  86966. }
  86967. if (this.shadowLevel > 0) {
  86968. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  86969. }
  86970. this._uniformBuffer.updateFloat("alpha", this.alpha);
  86971. // Point size
  86972. if (this.pointsCloud) {
  86973. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  86974. }
  86975. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  86976. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  86977. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  86978. }
  86979. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  86980. // Textures
  86981. if (scene.texturesEnabled) {
  86982. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86983. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  86984. }
  86985. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86986. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  86987. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  86988. }
  86989. else if (!defines.REFLECTIONBLUR) {
  86990. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  86991. }
  86992. else {
  86993. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  86994. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  86995. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  86996. }
  86997. if (defines.REFLECTIONFRESNEL) {
  86998. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  86999. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87000. }
  87001. }
  87002. }
  87003. // Clip plane
  87004. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87005. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87006. }
  87007. if (mustRebind || !this.isFrozen) {
  87008. if (scene.lightsEnabled) {
  87009. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87010. }
  87011. // View
  87012. this.bindView(effect);
  87013. // Fog
  87014. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87015. // image processing
  87016. this._imageProcessingConfiguration.bind(this._activeEffect);
  87017. }
  87018. this._uniformBuffer.update();
  87019. this._afterBind(mesh);
  87020. };
  87021. /**
  87022. * Dispose the material.
  87023. * @param forceDisposeEffect Force disposal of the associated effect.
  87024. * @param forceDisposeTextures Force disposal of the associated textures.
  87025. */
  87026. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87027. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87028. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87029. if (forceDisposeTextures) {
  87030. if (this.diffuseTexture) {
  87031. this.diffuseTexture.dispose();
  87032. }
  87033. if (this.reflectionTexture) {
  87034. this.reflectionTexture.dispose();
  87035. }
  87036. }
  87037. this._renderTargets.dispose();
  87038. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87039. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87040. }
  87041. _super.prototype.dispose.call(this, forceDisposeEffect);
  87042. };
  87043. /**
  87044. * Clones the material.
  87045. * @param name The cloned name.
  87046. * @returns The cloned material.
  87047. */
  87048. BackgroundMaterial.prototype.clone = function (name) {
  87049. var _this = this;
  87050. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87051. };
  87052. /**
  87053. * Serializes the current material to its JSON representation.
  87054. * @returns The JSON representation.
  87055. */
  87056. BackgroundMaterial.prototype.serialize = function () {
  87057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87058. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87059. return serializationObject;
  87060. };
  87061. /**
  87062. * Gets the class name of the material
  87063. * @returns "BackgroundMaterial"
  87064. */
  87065. BackgroundMaterial.prototype.getClassName = function () {
  87066. return "BackgroundMaterial";
  87067. };
  87068. /**
  87069. * Parse a JSON input to create back a background material.
  87070. * @param source The JSON data to parse
  87071. * @param scene The scene to create the parsed material in
  87072. * @param rootUrl The root url of the assets the material depends upon
  87073. * @returns the instantiated BackgroundMaterial.
  87074. */
  87075. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87076. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87077. };
  87078. /**
  87079. * Standard reflectance value at parallel view angle.
  87080. */
  87081. BackgroundMaterial.StandardReflectance0 = 0.05;
  87082. /**
  87083. * Standard reflectance value at grazing angle.
  87084. */
  87085. BackgroundMaterial.StandardReflectance90 = 0.5;
  87086. __decorate([
  87087. BABYLON.serializeAsColor3()
  87088. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87089. __decorate([
  87090. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87091. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87092. __decorate([
  87093. BABYLON.serialize()
  87094. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87095. __decorate([
  87096. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87097. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87098. __decorate([
  87099. BABYLON.serializeAsColor3()
  87100. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87101. __decorate([
  87102. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87103. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87104. __decorate([
  87105. BABYLON.serialize()
  87106. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87107. __decorate([
  87108. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87109. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87110. __decorate([
  87111. BABYLON.serializeAsColor3()
  87112. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87113. __decorate([
  87114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87115. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87116. __decorate([
  87117. BABYLON.serialize()
  87118. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87119. __decorate([
  87120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87121. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87122. __decorate([
  87123. BABYLON.serializeAsTexture()
  87124. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87125. __decorate([
  87126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87127. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87128. __decorate([
  87129. BABYLON.serialize()
  87130. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87131. __decorate([
  87132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87133. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87134. __decorate([
  87135. BABYLON.serializeAsTexture()
  87136. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87137. __decorate([
  87138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87139. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87140. __decorate([
  87141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87142. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87143. __decorate([
  87144. BABYLON.serialize()
  87145. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87146. __decorate([
  87147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87148. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87149. __decorate([
  87150. BABYLON.serialize()
  87151. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87152. __decorate([
  87153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87154. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87155. __decorate([
  87156. BABYLON.serializeAsVector3()
  87157. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87158. __decorate([
  87159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87160. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87161. __decorate([
  87162. BABYLON.serialize()
  87163. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87164. __decorate([
  87165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87166. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87167. __decorate([
  87168. BABYLON.serialize()
  87169. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87170. __decorate([
  87171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87172. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87173. __decorate([
  87174. BABYLON.serialize()
  87175. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87176. __decorate([
  87177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87178. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87179. __decorate([
  87180. BABYLON.serialize()
  87181. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87182. __decorate([
  87183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87184. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87185. __decorate([
  87186. BABYLON.serialize()
  87187. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87188. __decorate([
  87189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87190. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87191. __decorate([
  87192. BABYLON.serialize()
  87193. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87194. __decorate([
  87195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87196. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87197. __decorate([
  87198. BABYLON.serialize()
  87199. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87200. __decorate([
  87201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87202. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87203. __decorate([
  87204. BABYLON.serialize()
  87205. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87206. __decorate([
  87207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87208. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87209. __decorate([
  87210. BABYLON.serialize()
  87211. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87212. __decorate([
  87213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87214. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87215. __decorate([
  87216. BABYLON.serializeAsImageProcessingConfiguration()
  87217. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87218. return BackgroundMaterial;
  87219. }(BABYLON.PushMaterial));
  87220. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87221. })(BABYLON || (BABYLON = {}));
  87222. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87223. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87224. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87225. s = arguments[i];
  87226. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87227. t[p] = s[p];
  87228. }
  87229. return t;
  87230. };
  87231. var BABYLON;
  87232. (function (BABYLON) {
  87233. /**
  87234. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87235. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87236. * It also helps with the default setup of your imageProcessing configuration.
  87237. */
  87238. var EnvironmentHelper = /** @class */ (function () {
  87239. /**
  87240. * constructor
  87241. * @param options
  87242. * @param scene The scene to add the material to
  87243. */
  87244. function EnvironmentHelper(options, scene) {
  87245. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87246. this._scene = scene;
  87247. this._setupBackground();
  87248. this._setupImageProcessing();
  87249. }
  87250. /**
  87251. * Creates the default options for the helper.
  87252. */
  87253. EnvironmentHelper._getDefaultOptions = function () {
  87254. return {
  87255. createGround: true,
  87256. groundSize: 15,
  87257. groundTexture: this._groundTextureCDNUrl,
  87258. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87259. groundOpacity: 0.9,
  87260. enableGroundShadow: true,
  87261. groundShadowLevel: 0.5,
  87262. enableGroundMirror: false,
  87263. groundMirrorSizeRatio: 0.3,
  87264. groundMirrorBlurKernel: 64,
  87265. groundMirrorAmount: 1,
  87266. groundMirrorFresnelWeight: 1,
  87267. groundMirrorFallOffDistance: 0,
  87268. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87269. groundYBias: 0.00001,
  87270. createSkybox: true,
  87271. skyboxSize: 20,
  87272. skyboxTexture: this._skyboxTextureCDNUrl,
  87273. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87274. backgroundYRotation: 0,
  87275. sizeAuto: true,
  87276. rootPosition: BABYLON.Vector3.Zero(),
  87277. setupImageProcessing: true,
  87278. environmentTexture: this._environmentTextureCDNUrl,
  87279. cameraExposure: 0.8,
  87280. cameraContrast: 1.2,
  87281. toneMappingEnabled: true,
  87282. };
  87283. };
  87284. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87285. /**
  87286. * Gets the root mesh created by the helper.
  87287. */
  87288. get: function () {
  87289. return this._rootMesh;
  87290. },
  87291. enumerable: true,
  87292. configurable: true
  87293. });
  87294. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87295. /**
  87296. * Gets the skybox created by the helper.
  87297. */
  87298. get: function () {
  87299. return this._skybox;
  87300. },
  87301. enumerable: true,
  87302. configurable: true
  87303. });
  87304. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87305. /**
  87306. * Gets the skybox texture created by the helper.
  87307. */
  87308. get: function () {
  87309. return this._skyboxTexture;
  87310. },
  87311. enumerable: true,
  87312. configurable: true
  87313. });
  87314. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87315. /**
  87316. * Gets the skybox material created by the helper.
  87317. */
  87318. get: function () {
  87319. return this._skyboxMaterial;
  87320. },
  87321. enumerable: true,
  87322. configurable: true
  87323. });
  87324. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87325. /**
  87326. * Gets the ground mesh created by the helper.
  87327. */
  87328. get: function () {
  87329. return this._ground;
  87330. },
  87331. enumerable: true,
  87332. configurable: true
  87333. });
  87334. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87335. /**
  87336. * Gets the ground texture created by the helper.
  87337. */
  87338. get: function () {
  87339. return this._groundTexture;
  87340. },
  87341. enumerable: true,
  87342. configurable: true
  87343. });
  87344. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87345. /**
  87346. * Gets the ground mirror created by the helper.
  87347. */
  87348. get: function () {
  87349. return this._groundMirror;
  87350. },
  87351. enumerable: true,
  87352. configurable: true
  87353. });
  87354. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87355. /**
  87356. * Gets the ground mirror render list to helps pushing the meshes
  87357. * you wish in the ground reflection.
  87358. */
  87359. get: function () {
  87360. if (this._groundMirror) {
  87361. return this._groundMirror.renderList;
  87362. }
  87363. return null;
  87364. },
  87365. enumerable: true,
  87366. configurable: true
  87367. });
  87368. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87369. /**
  87370. * Gets the ground material created by the helper.
  87371. */
  87372. get: function () {
  87373. return this._groundMaterial;
  87374. },
  87375. enumerable: true,
  87376. configurable: true
  87377. });
  87378. /**
  87379. * Updates the background according to the new options
  87380. * @param options
  87381. */
  87382. EnvironmentHelper.prototype.updateOptions = function (options) {
  87383. var newOptions = __assign({}, this._options, options);
  87384. if (this._ground && !newOptions.createGround) {
  87385. this._ground.dispose();
  87386. this._ground = null;
  87387. }
  87388. if (this._groundMaterial && !newOptions.createGround) {
  87389. this._groundMaterial.dispose();
  87390. this._groundMaterial = null;
  87391. }
  87392. if (this._groundTexture) {
  87393. if (this._options.groundTexture != newOptions.groundTexture) {
  87394. this._groundTexture.dispose();
  87395. this._groundTexture = null;
  87396. }
  87397. }
  87398. if (this._skybox && !newOptions.createSkybox) {
  87399. this._skybox.dispose();
  87400. this._skybox = null;
  87401. }
  87402. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87403. this._skyboxMaterial.dispose();
  87404. this._skyboxMaterial = null;
  87405. }
  87406. if (this._skyboxTexture) {
  87407. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87408. this._skyboxTexture.dispose();
  87409. this._skyboxTexture = null;
  87410. }
  87411. }
  87412. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87413. this._groundMirror.dispose();
  87414. this._groundMirror = null;
  87415. }
  87416. if (this._scene.environmentTexture) {
  87417. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87418. this._scene.environmentTexture.dispose();
  87419. }
  87420. }
  87421. this._options = newOptions;
  87422. this._setupBackground();
  87423. this._setupImageProcessing();
  87424. };
  87425. /**
  87426. * Sets the primary color of all the available elements.
  87427. * @param color
  87428. */
  87429. EnvironmentHelper.prototype.setMainColor = function (color) {
  87430. if (this.groundMaterial) {
  87431. this.groundMaterial.primaryColor = color;
  87432. }
  87433. if (this.skyboxMaterial) {
  87434. this.skyboxMaterial.primaryColor = color;
  87435. }
  87436. if (this.groundMirror) {
  87437. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87438. }
  87439. };
  87440. /**
  87441. * Setup the image processing according to the specified options.
  87442. */
  87443. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87444. if (this._options.setupImageProcessing) {
  87445. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87446. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87447. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87448. this._setupEnvironmentTexture();
  87449. }
  87450. };
  87451. /**
  87452. * Setup the environment texture according to the specified options.
  87453. */
  87454. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87455. if (this._scene.environmentTexture) {
  87456. return;
  87457. }
  87458. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87459. this._scene.environmentTexture = this._options.environmentTexture;
  87460. return;
  87461. }
  87462. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87463. this._scene.environmentTexture = environmentTexture;
  87464. };
  87465. /**
  87466. * Setup the background according to the specified options.
  87467. */
  87468. EnvironmentHelper.prototype._setupBackground = function () {
  87469. if (!this._rootMesh) {
  87470. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87471. }
  87472. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87473. var sceneSize = this._getSceneSize();
  87474. if (this._options.createGround) {
  87475. this._setupGround(sceneSize);
  87476. this._setupGroundMaterial();
  87477. this._setupGroundDiffuseTexture();
  87478. if (this._options.enableGroundMirror) {
  87479. this._setupGroundMirrorTexture(sceneSize);
  87480. }
  87481. this._setupMirrorInGroundMaterial();
  87482. }
  87483. if (this._options.createSkybox) {
  87484. this._setupSkybox(sceneSize);
  87485. this._setupSkyboxMaterial();
  87486. this._setupSkyboxReflectionTexture();
  87487. }
  87488. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87489. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87490. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87491. };
  87492. /**
  87493. * Get the scene sizes according to the setup.
  87494. */
  87495. EnvironmentHelper.prototype._getSceneSize = function () {
  87496. var groundSize = this._options.groundSize;
  87497. var skyboxSize = this._options.skyboxSize;
  87498. var rootPosition = this._options.rootPosition;
  87499. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87500. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87501. }
  87502. var sceneExtends = this._scene.getWorldExtends();
  87503. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87504. if (this._options.sizeAuto) {
  87505. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87506. this._scene.activeCamera.upperRadiusLimit) {
  87507. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87508. skyboxSize = groundSize;
  87509. }
  87510. var sceneDiagonalLenght = sceneDiagonal.length();
  87511. if (sceneDiagonalLenght > groundSize) {
  87512. groundSize = sceneDiagonalLenght * 2;
  87513. skyboxSize = groundSize;
  87514. }
  87515. // 10 % bigger.
  87516. groundSize *= 1.1;
  87517. skyboxSize *= 1.5;
  87518. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87519. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87520. }
  87521. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87522. };
  87523. /**
  87524. * Setup the ground according to the specified options.
  87525. */
  87526. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87527. var _this = this;
  87528. if (!this._ground) {
  87529. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87530. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87531. this._ground.parent = this._rootMesh;
  87532. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87533. }
  87534. this._ground.receiveShadows = this._options.enableGroundShadow;
  87535. };
  87536. /**
  87537. * Setup the ground material according to the specified options.
  87538. */
  87539. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87540. if (!this._groundMaterial) {
  87541. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87542. }
  87543. this._groundMaterial.alpha = this._options.groundOpacity;
  87544. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87545. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87546. this._groundMaterial.primaryLevel = 1;
  87547. this._groundMaterial.primaryColor = this._options.groundColor;
  87548. this._groundMaterial.secondaryLevel = 0;
  87549. this._groundMaterial.tertiaryLevel = 0;
  87550. this._groundMaterial.useRGBColor = false;
  87551. this._groundMaterial.enableNoise = true;
  87552. if (this._ground) {
  87553. this._ground.material = this._groundMaterial;
  87554. }
  87555. };
  87556. /**
  87557. * Setup the ground diffuse texture according to the specified options.
  87558. */
  87559. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87560. if (!this._groundMaterial) {
  87561. return;
  87562. }
  87563. if (this._groundTexture) {
  87564. return;
  87565. }
  87566. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87567. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87568. return;
  87569. }
  87570. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87571. diffuseTexture.gammaSpace = false;
  87572. diffuseTexture.hasAlpha = true;
  87573. this._groundMaterial.diffuseTexture = diffuseTexture;
  87574. };
  87575. /**
  87576. * Setup the ground mirror texture according to the specified options.
  87577. */
  87578. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87579. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87580. if (!this._groundMirror) {
  87581. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87582. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87583. this._groundMirror.anisotropicFilteringLevel = 1;
  87584. this._groundMirror.wrapU = wrapping;
  87585. this._groundMirror.wrapV = wrapping;
  87586. this._groundMirror.gammaSpace = false;
  87587. if (this._groundMirror.renderList) {
  87588. for (var i = 0; i < this._scene.meshes.length; i++) {
  87589. var mesh = this._scene.meshes[i];
  87590. if (mesh !== this._ground &&
  87591. mesh !== this._skybox &&
  87592. mesh !== this._rootMesh) {
  87593. this._groundMirror.renderList.push(mesh);
  87594. }
  87595. }
  87596. }
  87597. }
  87598. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87599. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87600. };
  87601. /**
  87602. * Setup the ground to receive the mirror texture.
  87603. */
  87604. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87605. if (this._groundMaterial) {
  87606. this._groundMaterial.reflectionTexture = this._groundMirror;
  87607. this._groundMaterial.reflectionFresnel = true;
  87608. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87609. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87610. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87611. }
  87612. };
  87613. /**
  87614. * Setup the skybox according to the specified options.
  87615. */
  87616. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87617. var _this = this;
  87618. if (!this._skybox) {
  87619. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87620. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87621. }
  87622. this._skybox.parent = this._rootMesh;
  87623. };
  87624. /**
  87625. * Setup the skybox material according to the specified options.
  87626. */
  87627. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87628. if (!this._skybox) {
  87629. return;
  87630. }
  87631. if (!this._skyboxMaterial) {
  87632. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87633. }
  87634. this._skyboxMaterial.useRGBColor = false;
  87635. this._skyboxMaterial.primaryLevel = 1;
  87636. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87637. this._skyboxMaterial.secondaryLevel = 0;
  87638. this._skyboxMaterial.tertiaryLevel = 0;
  87639. this._skyboxMaterial.enableNoise = true;
  87640. this._skybox.material = this._skyboxMaterial;
  87641. };
  87642. /**
  87643. * Setup the skybox reflection texture according to the specified options.
  87644. */
  87645. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87646. if (!this._skyboxMaterial) {
  87647. return;
  87648. }
  87649. if (this._skyboxTexture) {
  87650. return;
  87651. }
  87652. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87653. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87654. return;
  87655. }
  87656. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87657. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87658. this._skyboxTexture.gammaSpace = false;
  87659. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87660. };
  87661. /**
  87662. * Dispose all the elements created by the Helper.
  87663. */
  87664. EnvironmentHelper.prototype.dispose = function () {
  87665. if (this._groundMaterial) {
  87666. this._groundMaterial.dispose(true, true);
  87667. }
  87668. if (this._skyboxMaterial) {
  87669. this._skyboxMaterial.dispose(true, true);
  87670. }
  87671. this._rootMesh.dispose(false);
  87672. };
  87673. /**
  87674. * Default ground texture URL.
  87675. */
  87676. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87677. /**
  87678. * Default skybox texture URL.
  87679. */
  87680. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87681. /**
  87682. * Default environment texture URL.
  87683. */
  87684. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87685. return EnvironmentHelper;
  87686. }());
  87687. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87688. })(BABYLON || (BABYLON = {}));
  87689. //# sourceMappingURL=babylon.environmentHelper.js.map
  87690. 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}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  87691. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  87692. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87693. var BABYLON;
  87694. (function (BABYLON) {
  87695. var GridMaterialDefines = /** @class */ (function (_super) {
  87696. __extends(GridMaterialDefines, _super);
  87697. function GridMaterialDefines() {
  87698. var _this = _super.call(this) || this;
  87699. _this.TRANSPARENT = false;
  87700. _this.FOG = false;
  87701. _this.PREMULTIPLYALPHA = false;
  87702. _this.rebuild();
  87703. return _this;
  87704. }
  87705. return GridMaterialDefines;
  87706. }(BABYLON.MaterialDefines));
  87707. /**
  87708. * The grid materials allows you to wrap any shape with a grid.
  87709. * Colors are customizable.
  87710. */
  87711. var GridMaterial = /** @class */ (function (_super) {
  87712. __extends(GridMaterial, _super);
  87713. /**
  87714. * constructor
  87715. * @param name The name given to the material in order to identify it afterwards.
  87716. * @param scene The scene the material is used in.
  87717. */
  87718. function GridMaterial(name, scene) {
  87719. var _this = _super.call(this, name, scene) || this;
  87720. /**
  87721. * Main color of the grid (e.g. between lines)
  87722. */
  87723. _this.mainColor = BABYLON.Color3.Black();
  87724. /**
  87725. * Color of the grid lines.
  87726. */
  87727. _this.lineColor = BABYLON.Color3.Teal();
  87728. /**
  87729. * The scale of the grid compared to unit.
  87730. */
  87731. _this.gridRatio = 1.0;
  87732. /**
  87733. * Allows setting an offset for the grid lines.
  87734. */
  87735. _this.gridOffset = BABYLON.Vector3.Zero();
  87736. /**
  87737. * The frequency of thicker lines.
  87738. */
  87739. _this.majorUnitFrequency = 10;
  87740. /**
  87741. * The visibility of minor units in the grid.
  87742. */
  87743. _this.minorUnitVisibility = 0.33;
  87744. /**
  87745. * The grid opacity outside of the lines.
  87746. */
  87747. _this.opacity = 1.0;
  87748. /**
  87749. * Determine RBG output is premultiplied by alpha value.
  87750. */
  87751. _this.preMultiplyAlpha = false;
  87752. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  87753. return _this;
  87754. }
  87755. /**
  87756. * Returns wehter or not the grid requires alpha blending.
  87757. */
  87758. GridMaterial.prototype.needAlphaBlending = function () {
  87759. return this.opacity < 1.0;
  87760. };
  87761. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  87762. return this.needAlphaBlending();
  87763. };
  87764. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87765. if (this.isFrozen) {
  87766. if (this._wasPreviouslyReady && subMesh.effect) {
  87767. return true;
  87768. }
  87769. }
  87770. if (!subMesh._materialDefines) {
  87771. subMesh._materialDefines = new GridMaterialDefines();
  87772. }
  87773. var defines = subMesh._materialDefines;
  87774. var scene = this.getScene();
  87775. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87776. if (this._renderId === scene.getRenderId()) {
  87777. return true;
  87778. }
  87779. }
  87780. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  87781. defines.TRANSPARENT = !defines.TRANSPARENT;
  87782. defines.markAsUnprocessed();
  87783. }
  87784. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  87785. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  87786. defines.markAsUnprocessed();
  87787. }
  87788. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  87789. // Get correct effect
  87790. if (defines.isDirty) {
  87791. defines.markAsProcessed();
  87792. scene.resetCachedMaterial();
  87793. // Attributes
  87794. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  87795. // Defines
  87796. var join = defines.toString();
  87797. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  87798. }
  87799. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87800. return false;
  87801. }
  87802. this._renderId = scene.getRenderId();
  87803. this._wasPreviouslyReady = true;
  87804. return true;
  87805. };
  87806. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87807. var scene = this.getScene();
  87808. var defines = subMesh._materialDefines;
  87809. if (!defines) {
  87810. return;
  87811. }
  87812. var effect = subMesh.effect;
  87813. if (!effect) {
  87814. return;
  87815. }
  87816. this._activeEffect = effect;
  87817. // Matrices
  87818. this.bindOnlyWorldMatrix(world);
  87819. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  87820. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  87821. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  87822. // Uniforms
  87823. if (this._mustRebind(scene, effect)) {
  87824. this._activeEffect.setColor3("mainColor", this.mainColor);
  87825. this._activeEffect.setColor3("lineColor", this.lineColor);
  87826. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  87827. this._gridControl.x = this.gridRatio;
  87828. this._gridControl.y = Math.round(this.majorUnitFrequency);
  87829. this._gridControl.z = this.minorUnitVisibility;
  87830. this._gridControl.w = this.opacity;
  87831. this._activeEffect.setVector4("gridControl", this._gridControl);
  87832. }
  87833. // Fog
  87834. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87835. this._afterBind(mesh, this._activeEffect);
  87836. };
  87837. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  87838. _super.prototype.dispose.call(this, forceDisposeEffect);
  87839. };
  87840. GridMaterial.prototype.clone = function (name) {
  87841. var _this = this;
  87842. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  87843. };
  87844. GridMaterial.prototype.serialize = function () {
  87845. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87846. serializationObject.customType = "BABYLON.GridMaterial";
  87847. return serializationObject;
  87848. };
  87849. GridMaterial.prototype.getClassName = function () {
  87850. return "GridMaterial";
  87851. };
  87852. GridMaterial.Parse = function (source, scene, rootUrl) {
  87853. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  87854. };
  87855. __decorate([
  87856. BABYLON.serializeAsColor3()
  87857. ], GridMaterial.prototype, "mainColor", void 0);
  87858. __decorate([
  87859. BABYLON.serializeAsColor3()
  87860. ], GridMaterial.prototype, "lineColor", void 0);
  87861. __decorate([
  87862. BABYLON.serialize()
  87863. ], GridMaterial.prototype, "gridRatio", void 0);
  87864. __decorate([
  87865. BABYLON.serializeAsColor3()
  87866. ], GridMaterial.prototype, "gridOffset", void 0);
  87867. __decorate([
  87868. BABYLON.serialize()
  87869. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  87870. __decorate([
  87871. BABYLON.serialize()
  87872. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  87873. __decorate([
  87874. BABYLON.serialize()
  87875. ], GridMaterial.prototype, "opacity", void 0);
  87876. __decorate([
  87877. BABYLON.serialize()
  87878. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  87879. return GridMaterial;
  87880. }(BABYLON.PushMaterial));
  87881. BABYLON.GridMaterial = GridMaterial;
  87882. })(BABYLON || (BABYLON = {}));
  87883. //# sourceMappingURL=babylon.gridmaterial.js.map
  87884. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  87885. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  87886. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87887. var BABYLON;
  87888. (function (BABYLON) {
  87889. var GLTFLoaderCoordinateSystemMode;
  87890. (function (GLTFLoaderCoordinateSystemMode) {
  87891. /**
  87892. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  87893. */
  87894. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  87895. /**
  87896. * Sets the useRightHandedSystem flag on the scene.
  87897. */
  87898. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  87899. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  87900. var GLTFLoaderAnimationStartMode;
  87901. (function (GLTFLoaderAnimationStartMode) {
  87902. /**
  87903. * No animation will start.
  87904. */
  87905. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  87906. /**
  87907. * The first animation will start.
  87908. */
  87909. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  87910. /**
  87911. * All animations will start.
  87912. */
  87913. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  87914. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  87915. var GLTFLoaderState;
  87916. (function (GLTFLoaderState) {
  87917. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  87918. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  87919. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  87920. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  87921. var GLTFFileLoader = /** @class */ (function () {
  87922. function GLTFFileLoader() {
  87923. // #region Common options
  87924. /**
  87925. * Raised when the asset has been parsed.
  87926. * The data.json property stores the glTF JSON.
  87927. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  87928. */
  87929. this.onParsedObservable = new BABYLON.Observable();
  87930. // #endregion
  87931. // #region V2 options
  87932. /**
  87933. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  87934. */
  87935. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  87936. /**
  87937. * The animation start mode (NONE, FIRST, ALL).
  87938. */
  87939. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  87940. /**
  87941. * Set to true to compile materials before raising the success callback.
  87942. */
  87943. this.compileMaterials = false;
  87944. /**
  87945. * Set to true to also compile materials with clip planes.
  87946. */
  87947. this.useClipPlane = false;
  87948. /**
  87949. * Set to true to compile shadow generators before raising the success callback.
  87950. */
  87951. this.compileShadowGenerators = false;
  87952. /**
  87953. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  87954. */
  87955. this.onMeshLoadedObservable = new BABYLON.Observable();
  87956. /**
  87957. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  87958. */
  87959. this.onTextureLoadedObservable = new BABYLON.Observable();
  87960. /**
  87961. * Raised when the loader creates a material after parsing the glTF properties of the material.
  87962. */
  87963. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87964. /**
  87965. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  87966. * For assets with LODs, raised when all of the LODs are complete.
  87967. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  87968. */
  87969. this.onCompleteObservable = new BABYLON.Observable();
  87970. /**
  87971. * Raised when the loader is disposed.
  87972. */
  87973. this.onDisposeObservable = new BABYLON.Observable();
  87974. /**
  87975. * Raised after a loader extension is created.
  87976. * Set additional options for a loader extension in this event.
  87977. */
  87978. this.onExtensionLoadedObservable = new BABYLON.Observable();
  87979. // #endregion
  87980. this._loader = null;
  87981. this.name = "gltf";
  87982. this.extensions = {
  87983. ".gltf": { isBinary: false },
  87984. ".glb": { isBinary: true }
  87985. };
  87986. }
  87987. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  87988. set: function (callback) {
  87989. if (this._onParsedObserver) {
  87990. this.onParsedObservable.remove(this._onParsedObserver);
  87991. }
  87992. this._onParsedObserver = this.onParsedObservable.add(callback);
  87993. },
  87994. enumerable: true,
  87995. configurable: true
  87996. });
  87997. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  87998. set: function (callback) {
  87999. if (this._onMeshLoadedObserver) {
  88000. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88001. }
  88002. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88003. },
  88004. enumerable: true,
  88005. configurable: true
  88006. });
  88007. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88008. set: function (callback) {
  88009. if (this._onTextureLoadedObserver) {
  88010. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88011. }
  88012. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88013. },
  88014. enumerable: true,
  88015. configurable: true
  88016. });
  88017. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88018. set: function (callback) {
  88019. if (this._onMaterialLoadedObserver) {
  88020. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88021. }
  88022. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88023. },
  88024. enumerable: true,
  88025. configurable: true
  88026. });
  88027. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88028. set: function (callback) {
  88029. if (this._onCompleteObserver) {
  88030. this.onCompleteObservable.remove(this._onCompleteObserver);
  88031. }
  88032. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88033. },
  88034. enumerable: true,
  88035. configurable: true
  88036. });
  88037. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88038. set: function (callback) {
  88039. if (this._onDisposeObserver) {
  88040. this.onDisposeObservable.remove(this._onDisposeObserver);
  88041. }
  88042. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88043. },
  88044. enumerable: true,
  88045. configurable: true
  88046. });
  88047. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88048. set: function (callback) {
  88049. if (this._onExtensionLoadedObserver) {
  88050. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88051. }
  88052. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88053. },
  88054. enumerable: true,
  88055. configurable: true
  88056. });
  88057. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88058. /**
  88059. * The loader state or null if not active.
  88060. */
  88061. get: function () {
  88062. return this._loader ? this._loader.state : null;
  88063. },
  88064. enumerable: true,
  88065. configurable: true
  88066. });
  88067. /**
  88068. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88069. */
  88070. GLTFFileLoader.prototype.dispose = function () {
  88071. if (this._loader) {
  88072. this._loader.dispose();
  88073. this._loader = null;
  88074. }
  88075. this.onMeshLoadedObservable.clear();
  88076. this.onTextureLoadedObservable.clear();
  88077. this.onMaterialLoadedObservable.clear();
  88078. this.onDisposeObservable.notifyObservers(this);
  88079. this.onDisposeObservable.clear();
  88080. };
  88081. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88082. var _this = this;
  88083. return Promise.resolve().then(function () {
  88084. var loaderData = _this._parse(data);
  88085. _this._loader = _this._getLoader(loaderData);
  88086. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88087. });
  88088. };
  88089. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88090. var _this = this;
  88091. return Promise.resolve().then(function () {
  88092. var loaderData = _this._parse(data);
  88093. _this._loader = _this._getLoader(loaderData);
  88094. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88095. });
  88096. };
  88097. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88098. var _this = this;
  88099. return Promise.resolve().then(function () {
  88100. var loaderData = _this._parse(data);
  88101. _this._loader = _this._getLoader(loaderData);
  88102. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88103. var container = new BABYLON.AssetContainer(scene);
  88104. Array.prototype.push.apply(container.meshes, result.meshes);
  88105. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88106. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88107. container.removeAllFromScene();
  88108. return container;
  88109. });
  88110. });
  88111. };
  88112. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88113. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88114. };
  88115. GLTFFileLoader.prototype.createPlugin = function () {
  88116. return new GLTFFileLoader();
  88117. };
  88118. GLTFFileLoader.prototype._parse = function (data) {
  88119. var parsedData;
  88120. if (data instanceof ArrayBuffer) {
  88121. parsedData = GLTFFileLoader._parseBinary(data);
  88122. }
  88123. else {
  88124. parsedData = {
  88125. json: JSON.parse(data),
  88126. bin: null
  88127. };
  88128. }
  88129. this.onParsedObservable.notifyObservers(parsedData);
  88130. this.onParsedObservable.clear();
  88131. return parsedData;
  88132. };
  88133. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88134. var _this = this;
  88135. var loaderVersion = { major: 2, minor: 0 };
  88136. var asset = loaderData.json.asset || {};
  88137. var version = GLTFFileLoader._parseVersion(asset.version);
  88138. if (!version) {
  88139. throw new Error("Invalid version: " + asset.version);
  88140. }
  88141. if (asset.minVersion !== undefined) {
  88142. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88143. if (!minVersion) {
  88144. throw new Error("Invalid minimum version: " + asset.minVersion);
  88145. }
  88146. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88147. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88148. }
  88149. }
  88150. var createLoaders = {
  88151. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88152. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88153. };
  88154. var createLoader = createLoaders[version.major];
  88155. if (!createLoader) {
  88156. throw new Error("Unsupported version: " + asset.version);
  88157. }
  88158. var loader = createLoader();
  88159. loader.coordinateSystemMode = this.coordinateSystemMode;
  88160. loader.animationStartMode = this.animationStartMode;
  88161. loader.compileMaterials = this.compileMaterials;
  88162. loader.useClipPlane = this.useClipPlane;
  88163. loader.compileShadowGenerators = this.compileShadowGenerators;
  88164. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88165. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88166. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88167. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88168. loader.onCompleteObservable.add(function () {
  88169. _this.onMeshLoadedObservable.clear();
  88170. _this.onTextureLoadedObservable.clear();
  88171. _this.onMaterialLoadedObservable.clear();
  88172. _this.onCompleteObservable.notifyObservers(_this);
  88173. _this.onCompleteObservable.clear();
  88174. });
  88175. return loader;
  88176. };
  88177. GLTFFileLoader._parseBinary = function (data) {
  88178. var Binary = {
  88179. Magic: 0x46546C67
  88180. };
  88181. var binaryReader = new BinaryReader(data);
  88182. var magic = binaryReader.readUint32();
  88183. if (magic !== Binary.Magic) {
  88184. throw new Error("Unexpected magic: " + magic);
  88185. }
  88186. var version = binaryReader.readUint32();
  88187. switch (version) {
  88188. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88189. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88190. }
  88191. throw new Error("Unsupported version: " + version);
  88192. };
  88193. GLTFFileLoader._parseV1 = function (binaryReader) {
  88194. var ContentFormat = {
  88195. JSON: 0
  88196. };
  88197. var length = binaryReader.readUint32();
  88198. if (length != binaryReader.getLength()) {
  88199. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88200. }
  88201. var contentLength = binaryReader.readUint32();
  88202. var contentFormat = binaryReader.readUint32();
  88203. var content;
  88204. switch (contentFormat) {
  88205. case ContentFormat.JSON: {
  88206. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88207. break;
  88208. }
  88209. default: {
  88210. throw new Error("Unexpected content format: " + contentFormat);
  88211. }
  88212. }
  88213. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88214. var body = binaryReader.readUint8Array(bytesRemaining);
  88215. return {
  88216. json: content,
  88217. bin: body
  88218. };
  88219. };
  88220. GLTFFileLoader._parseV2 = function (binaryReader) {
  88221. var ChunkFormat = {
  88222. JSON: 0x4E4F534A,
  88223. BIN: 0x004E4942
  88224. };
  88225. var length = binaryReader.readUint32();
  88226. if (length !== binaryReader.getLength()) {
  88227. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88228. }
  88229. // JSON chunk
  88230. var chunkLength = binaryReader.readUint32();
  88231. var chunkFormat = binaryReader.readUint32();
  88232. if (chunkFormat !== ChunkFormat.JSON) {
  88233. throw new Error("First chunk format is not JSON");
  88234. }
  88235. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88236. // Look for BIN chunk
  88237. var bin = null;
  88238. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88239. var chunkLength_1 = binaryReader.readUint32();
  88240. var chunkFormat_1 = binaryReader.readUint32();
  88241. switch (chunkFormat_1) {
  88242. case ChunkFormat.JSON: {
  88243. throw new Error("Unexpected JSON chunk");
  88244. }
  88245. case ChunkFormat.BIN: {
  88246. bin = binaryReader.readUint8Array(chunkLength_1);
  88247. break;
  88248. }
  88249. default: {
  88250. // ignore unrecognized chunkFormat
  88251. binaryReader.skipBytes(chunkLength_1);
  88252. break;
  88253. }
  88254. }
  88255. }
  88256. return {
  88257. json: json,
  88258. bin: bin
  88259. };
  88260. };
  88261. GLTFFileLoader._parseVersion = function (version) {
  88262. if (version === "1.0" || version === "1.0.1") {
  88263. return {
  88264. major: 1,
  88265. minor: 0
  88266. };
  88267. }
  88268. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88269. if (!match) {
  88270. return null;
  88271. }
  88272. return {
  88273. major: parseInt(match[1]),
  88274. minor: parseInt(match[2])
  88275. };
  88276. };
  88277. GLTFFileLoader._compareVersion = function (a, b) {
  88278. if (a.major > b.major)
  88279. return 1;
  88280. if (a.major < b.major)
  88281. return -1;
  88282. if (a.minor > b.minor)
  88283. return 1;
  88284. if (a.minor < b.minor)
  88285. return -1;
  88286. return 0;
  88287. };
  88288. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88289. var result = "";
  88290. var length = buffer.byteLength;
  88291. for (var i = 0; i < length; i++) {
  88292. result += String.fromCharCode(buffer[i]);
  88293. }
  88294. return result;
  88295. };
  88296. // #endregion
  88297. // #region V1 options
  88298. GLTFFileLoader.IncrementalLoading = true;
  88299. GLTFFileLoader.HomogeneousCoordinates = false;
  88300. return GLTFFileLoader;
  88301. }());
  88302. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88303. var BinaryReader = /** @class */ (function () {
  88304. function BinaryReader(arrayBuffer) {
  88305. this._arrayBuffer = arrayBuffer;
  88306. this._dataView = new DataView(arrayBuffer);
  88307. this._byteOffset = 0;
  88308. }
  88309. BinaryReader.prototype.getPosition = function () {
  88310. return this._byteOffset;
  88311. };
  88312. BinaryReader.prototype.getLength = function () {
  88313. return this._arrayBuffer.byteLength;
  88314. };
  88315. BinaryReader.prototype.readUint32 = function () {
  88316. var value = this._dataView.getUint32(this._byteOffset, true);
  88317. this._byteOffset += 4;
  88318. return value;
  88319. };
  88320. BinaryReader.prototype.readUint8Array = function (length) {
  88321. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88322. this._byteOffset += length;
  88323. return value;
  88324. };
  88325. BinaryReader.prototype.skipBytes = function (length) {
  88326. this._byteOffset += length;
  88327. };
  88328. return BinaryReader;
  88329. }());
  88330. if (BABYLON.SceneLoader) {
  88331. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88332. }
  88333. })(BABYLON || (BABYLON = {}));
  88334. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88335. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88336. var BABYLON;
  88337. (function (BABYLON) {
  88338. var GLTF1;
  88339. (function (GLTF1) {
  88340. /**
  88341. * Enums
  88342. */
  88343. var EComponentType;
  88344. (function (EComponentType) {
  88345. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88346. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88347. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88348. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88349. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88350. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88351. var EShaderType;
  88352. (function (EShaderType) {
  88353. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88354. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88355. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88356. var EParameterType;
  88357. (function (EParameterType) {
  88358. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88359. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88360. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88361. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88362. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88363. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88364. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88365. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88366. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88367. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88368. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88369. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88370. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88371. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88372. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88373. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88374. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88375. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88376. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88377. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88378. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88379. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88380. var ETextureWrapMode;
  88381. (function (ETextureWrapMode) {
  88382. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88383. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88384. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88385. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88386. var ETextureFilterType;
  88387. (function (ETextureFilterType) {
  88388. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88389. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88390. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88391. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88392. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88393. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88394. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88395. var ETextureFormat;
  88396. (function (ETextureFormat) {
  88397. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88398. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88399. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88400. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88401. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88402. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88403. var ECullingType;
  88404. (function (ECullingType) {
  88405. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88406. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88407. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88408. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88409. var EBlendingFunction;
  88410. (function (EBlendingFunction) {
  88411. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88412. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88413. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88414. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88415. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88416. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88417. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88418. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88419. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88420. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88421. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88422. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88423. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88424. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88425. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88426. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88427. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88428. })(BABYLON || (BABYLON = {}));
  88429. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88430. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88431. var BABYLON;
  88432. (function (BABYLON) {
  88433. var GLTF1;
  88434. (function (GLTF1) {
  88435. /**
  88436. * Tokenizer. Used for shaders compatibility
  88437. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88438. */
  88439. var ETokenType;
  88440. (function (ETokenType) {
  88441. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88442. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88443. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88444. })(ETokenType || (ETokenType = {}));
  88445. var Tokenizer = /** @class */ (function () {
  88446. function Tokenizer(toParse) {
  88447. this._pos = 0;
  88448. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88449. this._toParse = toParse;
  88450. this._maxPos = toParse.length;
  88451. }
  88452. Tokenizer.prototype.getNextToken = function () {
  88453. if (this.isEnd())
  88454. return ETokenType.END_OF_INPUT;
  88455. this.currentString = this.read();
  88456. this.currentToken = ETokenType.UNKNOWN;
  88457. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88458. this.currentToken = ETokenType.IDENTIFIER;
  88459. this.currentIdentifier = this.currentString;
  88460. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88461. this.currentIdentifier += this.currentString;
  88462. this.forward();
  88463. }
  88464. }
  88465. return this.currentToken;
  88466. };
  88467. Tokenizer.prototype.peek = function () {
  88468. return this._toParse[this._pos];
  88469. };
  88470. Tokenizer.prototype.read = function () {
  88471. return this._toParse[this._pos++];
  88472. };
  88473. Tokenizer.prototype.forward = function () {
  88474. this._pos++;
  88475. };
  88476. Tokenizer.prototype.isEnd = function () {
  88477. return this._pos >= this._maxPos;
  88478. };
  88479. return Tokenizer;
  88480. }());
  88481. /**
  88482. * Values
  88483. */
  88484. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88485. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88486. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88487. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88488. /**
  88489. * Parse
  88490. */
  88491. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88492. for (var buf in parsedBuffers) {
  88493. var parsedBuffer = parsedBuffers[buf];
  88494. gltfRuntime.buffers[buf] = parsedBuffer;
  88495. gltfRuntime.buffersCount++;
  88496. }
  88497. };
  88498. var parseShaders = function (parsedShaders, gltfRuntime) {
  88499. for (var sha in parsedShaders) {
  88500. var parsedShader = parsedShaders[sha];
  88501. gltfRuntime.shaders[sha] = parsedShader;
  88502. gltfRuntime.shaderscount++;
  88503. }
  88504. };
  88505. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88506. for (var object in parsedObjects) {
  88507. var parsedObject = parsedObjects[object];
  88508. gltfRuntime[runtimeProperty][object] = parsedObject;
  88509. }
  88510. };
  88511. /**
  88512. * Utils
  88513. */
  88514. var normalizeUVs = function (buffer) {
  88515. if (!buffer) {
  88516. return;
  88517. }
  88518. for (var i = 0; i < buffer.length / 2; i++) {
  88519. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88520. }
  88521. };
  88522. var getAttribute = function (attributeParameter) {
  88523. if (attributeParameter.semantic === "NORMAL") {
  88524. return "normal";
  88525. }
  88526. else if (attributeParameter.semantic === "POSITION") {
  88527. return "position";
  88528. }
  88529. else if (attributeParameter.semantic === "JOINT") {
  88530. return "matricesIndices";
  88531. }
  88532. else if (attributeParameter.semantic === "WEIGHT") {
  88533. return "matricesWeights";
  88534. }
  88535. else if (attributeParameter.semantic === "COLOR") {
  88536. return "color";
  88537. }
  88538. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88539. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88540. return "uv" + (channel === 0 ? "" : channel + 1);
  88541. }
  88542. return null;
  88543. };
  88544. /**
  88545. * Loads and creates animations
  88546. */
  88547. var loadAnimations = function (gltfRuntime) {
  88548. for (var anim in gltfRuntime.animations) {
  88549. var animation = gltfRuntime.animations[anim];
  88550. if (!animation.channels || !animation.samplers) {
  88551. continue;
  88552. }
  88553. var lastAnimation = null;
  88554. for (var i = 0; i < animation.channels.length; i++) {
  88555. // Get parameters and load buffers
  88556. var channel = animation.channels[i];
  88557. var sampler = animation.samplers[channel.sampler];
  88558. if (!sampler) {
  88559. continue;
  88560. }
  88561. var inputData = null;
  88562. var outputData = null;
  88563. if (animation.parameters) {
  88564. inputData = animation.parameters[sampler.input];
  88565. outputData = animation.parameters[sampler.output];
  88566. }
  88567. else {
  88568. inputData = sampler.input;
  88569. outputData = sampler.output;
  88570. }
  88571. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88572. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88573. var targetID = channel.target.id;
  88574. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88575. if (targetNode === null) {
  88576. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88577. }
  88578. if (targetNode === null) {
  88579. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88580. continue;
  88581. }
  88582. var isBone = targetNode instanceof BABYLON.Bone;
  88583. // Get target path (position, rotation or scaling)
  88584. var targetPath = channel.target.path;
  88585. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88586. if (targetPathIndex !== -1) {
  88587. targetPath = babylonAnimationPaths[targetPathIndex];
  88588. }
  88589. // Determine animation type
  88590. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88591. if (!isBone) {
  88592. if (targetPath === "rotationQuaternion") {
  88593. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88594. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88595. }
  88596. else {
  88597. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88598. }
  88599. }
  88600. // Create animation and key frames
  88601. var babylonAnimation = null;
  88602. var keys = [];
  88603. var arrayOffset = 0;
  88604. var modifyKey = false;
  88605. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88606. babylonAnimation = lastAnimation;
  88607. modifyKey = true;
  88608. }
  88609. if (!modifyKey) {
  88610. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88611. }
  88612. // For each frame
  88613. for (var j = 0; j < bufferInput.length; j++) {
  88614. var value = null;
  88615. if (targetPath === "rotationQuaternion") {
  88616. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88617. arrayOffset += 4;
  88618. }
  88619. else {
  88620. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88621. arrayOffset += 3;
  88622. }
  88623. if (isBone) {
  88624. var bone = targetNode;
  88625. var translation = BABYLON.Vector3.Zero();
  88626. var rotationQuaternion = new BABYLON.Quaternion();
  88627. var scaling = BABYLON.Vector3.Zero();
  88628. // Warning on decompose
  88629. var mat = bone.getBaseMatrix();
  88630. if (modifyKey && lastAnimation) {
  88631. mat = lastAnimation.getKeys()[j].value;
  88632. }
  88633. mat.decompose(scaling, rotationQuaternion, translation);
  88634. if (targetPath === "position") {
  88635. translation = value;
  88636. }
  88637. else if (targetPath === "rotationQuaternion") {
  88638. rotationQuaternion = value;
  88639. }
  88640. else {
  88641. scaling = value;
  88642. }
  88643. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88644. }
  88645. if (!modifyKey) {
  88646. keys.push({
  88647. frame: bufferInput[j],
  88648. value: value
  88649. });
  88650. }
  88651. else if (lastAnimation) {
  88652. lastAnimation.getKeys()[j].value = value;
  88653. }
  88654. }
  88655. // Finish
  88656. if (!modifyKey && babylonAnimation) {
  88657. babylonAnimation.setKeys(keys);
  88658. targetNode.animations.push(babylonAnimation);
  88659. }
  88660. lastAnimation = babylonAnimation;
  88661. gltfRuntime.scene.stopAnimation(targetNode);
  88662. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88663. }
  88664. }
  88665. };
  88666. /**
  88667. * Returns the bones transformation matrix
  88668. */
  88669. var configureBoneTransformation = function (node) {
  88670. var mat = null;
  88671. if (node.translation || node.rotation || node.scale) {
  88672. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88673. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88674. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88675. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88676. }
  88677. else {
  88678. mat = BABYLON.Matrix.FromArray(node.matrix);
  88679. }
  88680. return mat;
  88681. };
  88682. /**
  88683. * Returns the parent bone
  88684. */
  88685. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88686. // Try to find
  88687. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88688. if (newSkeleton.bones[i].name === jointName) {
  88689. return newSkeleton.bones[i];
  88690. }
  88691. }
  88692. // Not found, search in gltf nodes
  88693. var nodes = gltfRuntime.nodes;
  88694. for (var nde in nodes) {
  88695. var node = nodes[nde];
  88696. if (!node.jointName) {
  88697. continue;
  88698. }
  88699. var children = node.children;
  88700. for (var i = 0; i < children.length; i++) {
  88701. var child = gltfRuntime.nodes[children[i]];
  88702. if (!child.jointName) {
  88703. continue;
  88704. }
  88705. if (child.jointName === jointName) {
  88706. var mat = configureBoneTransformation(node);
  88707. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88708. bone.id = nde;
  88709. return bone;
  88710. }
  88711. }
  88712. }
  88713. return null;
  88714. };
  88715. /**
  88716. * Returns the appropriate root node
  88717. */
  88718. var getNodeToRoot = function (nodesToRoot, id) {
  88719. for (var i = 0; i < nodesToRoot.length; i++) {
  88720. var nodeToRoot = nodesToRoot[i];
  88721. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88722. var child = nodeToRoot.node.children[j];
  88723. if (child === id) {
  88724. return nodeToRoot.bone;
  88725. }
  88726. }
  88727. }
  88728. return null;
  88729. };
  88730. /**
  88731. * Returns the node with the joint name
  88732. */
  88733. var getJointNode = function (gltfRuntime, jointName) {
  88734. var nodes = gltfRuntime.nodes;
  88735. var node = nodes[jointName];
  88736. if (node) {
  88737. return {
  88738. node: node,
  88739. id: jointName
  88740. };
  88741. }
  88742. for (var nde in nodes) {
  88743. node = nodes[nde];
  88744. if (node.jointName === jointName) {
  88745. return {
  88746. node: node,
  88747. id: nde
  88748. };
  88749. }
  88750. }
  88751. return null;
  88752. };
  88753. /**
  88754. * Checks if a nodes is in joints
  88755. */
  88756. var nodeIsInJoints = function (skins, id) {
  88757. for (var i = 0; i < skins.jointNames.length; i++) {
  88758. if (skins.jointNames[i] === id) {
  88759. return true;
  88760. }
  88761. }
  88762. return false;
  88763. };
  88764. /**
  88765. * Fills the nodes to root for bones and builds hierarchy
  88766. */
  88767. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  88768. // Creates nodes for root
  88769. for (var nde in gltfRuntime.nodes) {
  88770. var node = gltfRuntime.nodes[nde];
  88771. var id = nde;
  88772. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  88773. continue;
  88774. }
  88775. // Create node to root bone
  88776. var mat = configureBoneTransformation(node);
  88777. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  88778. bone.id = id;
  88779. nodesToRoot.push({ bone: bone, node: node, id: id });
  88780. }
  88781. // Parenting
  88782. for (var i = 0; i < nodesToRoot.length; i++) {
  88783. var nodeToRoot = nodesToRoot[i];
  88784. var children = nodeToRoot.node.children;
  88785. for (var j = 0; j < children.length; j++) {
  88786. var child = null;
  88787. for (var k = 0; k < nodesToRoot.length; k++) {
  88788. if (nodesToRoot[k].id === children[j]) {
  88789. child = nodesToRoot[k];
  88790. break;
  88791. }
  88792. }
  88793. if (child) {
  88794. child.bone._parent = nodeToRoot.bone;
  88795. nodeToRoot.bone.children.push(child.bone);
  88796. }
  88797. }
  88798. }
  88799. };
  88800. /**
  88801. * Imports a skeleton
  88802. */
  88803. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  88804. if (!newSkeleton) {
  88805. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  88806. }
  88807. if (!skins.babylonSkeleton) {
  88808. return newSkeleton;
  88809. }
  88810. // Find the root bones
  88811. var nodesToRoot = [];
  88812. var nodesToRootToAdd = [];
  88813. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  88814. newSkeleton.bones = [];
  88815. // Joints
  88816. for (var i = 0; i < skins.jointNames.length; i++) {
  88817. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88818. if (!jointNode) {
  88819. continue;
  88820. }
  88821. var node = jointNode.node;
  88822. if (!node) {
  88823. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  88824. continue;
  88825. }
  88826. var id = jointNode.id;
  88827. // Optimize, if the bone already exists...
  88828. var existingBone = gltfRuntime.scene.getBoneByID(id);
  88829. if (existingBone) {
  88830. newSkeleton.bones.push(existingBone);
  88831. continue;
  88832. }
  88833. // Search for parent bone
  88834. var foundBone = false;
  88835. var parentBone = null;
  88836. for (var j = 0; j < i; j++) {
  88837. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  88838. if (!jointNode_1) {
  88839. continue;
  88840. }
  88841. var joint = jointNode_1.node;
  88842. if (!joint) {
  88843. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  88844. continue;
  88845. }
  88846. var children = joint.children;
  88847. if (!children) {
  88848. continue;
  88849. }
  88850. foundBone = false;
  88851. for (var k = 0; k < children.length; k++) {
  88852. if (children[k] === id) {
  88853. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  88854. foundBone = true;
  88855. break;
  88856. }
  88857. }
  88858. if (foundBone) {
  88859. break;
  88860. }
  88861. }
  88862. // Create bone
  88863. var mat = configureBoneTransformation(node);
  88864. if (!parentBone && nodesToRoot.length > 0) {
  88865. parentBone = getNodeToRoot(nodesToRoot, id);
  88866. if (parentBone) {
  88867. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  88868. nodesToRootToAdd.push(parentBone);
  88869. }
  88870. }
  88871. }
  88872. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  88873. bone.id = id;
  88874. }
  88875. // Polish
  88876. var bones = newSkeleton.bones;
  88877. newSkeleton.bones = [];
  88878. for (var i = 0; i < skins.jointNames.length; i++) {
  88879. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88880. if (!jointNode) {
  88881. continue;
  88882. }
  88883. for (var j = 0; j < bones.length; j++) {
  88884. if (bones[j].id === jointNode.id) {
  88885. newSkeleton.bones.push(bones[j]);
  88886. break;
  88887. }
  88888. }
  88889. }
  88890. newSkeleton.prepare();
  88891. // Finish
  88892. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  88893. newSkeleton.bones.push(nodesToRootToAdd[i]);
  88894. }
  88895. return newSkeleton;
  88896. };
  88897. /**
  88898. * Imports a mesh and its geometries
  88899. */
  88900. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  88901. if (!newMesh) {
  88902. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  88903. newMesh.id = id;
  88904. }
  88905. if (!node.babylonNode) {
  88906. return newMesh;
  88907. }
  88908. var subMaterials = [];
  88909. var vertexData = null;
  88910. var verticesStarts = new Array();
  88911. var verticesCounts = new Array();
  88912. var indexStarts = new Array();
  88913. var indexCounts = new Array();
  88914. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  88915. var meshID = meshes[meshIndex];
  88916. var mesh = gltfRuntime.meshes[meshID];
  88917. if (!mesh) {
  88918. continue;
  88919. }
  88920. // Positions, normals and UVs
  88921. for (var i = 0; i < mesh.primitives.length; i++) {
  88922. // Temporary vertex data
  88923. var tempVertexData = new BABYLON.VertexData();
  88924. var primitive = mesh.primitives[i];
  88925. if (primitive.mode !== 4) {
  88926. // continue;
  88927. }
  88928. var attributes = primitive.attributes;
  88929. var accessor = null;
  88930. var buffer = null;
  88931. // Set positions, normal and uvs
  88932. for (var semantic in attributes) {
  88933. // Link accessor and buffer view
  88934. accessor = gltfRuntime.accessors[attributes[semantic]];
  88935. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  88936. if (semantic === "NORMAL") {
  88937. tempVertexData.normals = new Float32Array(buffer.length);
  88938. tempVertexData.normals.set(buffer);
  88939. }
  88940. else if (semantic === "POSITION") {
  88941. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  88942. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  88943. for (var j = 0; j < buffer.length; j += 4) {
  88944. tempVertexData.positions[j] = buffer[j];
  88945. tempVertexData.positions[j + 1] = buffer[j + 1];
  88946. tempVertexData.positions[j + 2] = buffer[j + 2];
  88947. }
  88948. }
  88949. else {
  88950. tempVertexData.positions = new Float32Array(buffer.length);
  88951. tempVertexData.positions.set(buffer);
  88952. }
  88953. verticesCounts.push(tempVertexData.positions.length);
  88954. }
  88955. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  88956. var channel = Number(semantic.split("_")[1]);
  88957. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  88958. var uvs = new Float32Array(buffer.length);
  88959. uvs.set(buffer);
  88960. normalizeUVs(uvs);
  88961. tempVertexData.set(uvs, uvKind);
  88962. }
  88963. else if (semantic === "JOINT") {
  88964. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  88965. tempVertexData.matricesIndices.set(buffer);
  88966. }
  88967. else if (semantic === "WEIGHT") {
  88968. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  88969. tempVertexData.matricesWeights.set(buffer);
  88970. }
  88971. else if (semantic === "COLOR") {
  88972. tempVertexData.colors = new Float32Array(buffer.length);
  88973. tempVertexData.colors.set(buffer);
  88974. }
  88975. }
  88976. // Indices
  88977. accessor = gltfRuntime.accessors[primitive.indices];
  88978. if (accessor) {
  88979. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  88980. tempVertexData.indices = new Int32Array(buffer.length);
  88981. tempVertexData.indices.set(buffer);
  88982. indexCounts.push(tempVertexData.indices.length);
  88983. }
  88984. else {
  88985. // Set indices on the fly
  88986. var indices = [];
  88987. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  88988. indices.push(j);
  88989. }
  88990. tempVertexData.indices = new Int32Array(indices);
  88991. indexCounts.push(tempVertexData.indices.length);
  88992. }
  88993. if (!vertexData) {
  88994. vertexData = tempVertexData;
  88995. }
  88996. else {
  88997. vertexData.merge(tempVertexData);
  88998. }
  88999. // Sub material
  89000. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89001. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89002. // Update vertices start and index start
  89003. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89004. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89005. }
  89006. }
  89007. var material;
  89008. if (subMaterials.length > 1) {
  89009. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89010. material.subMaterials = subMaterials;
  89011. }
  89012. else {
  89013. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89014. }
  89015. if (subMaterials.length === 1) {
  89016. material = subMaterials[0];
  89017. }
  89018. if (!newMesh.material) {
  89019. newMesh.material = material;
  89020. }
  89021. // Apply geometry
  89022. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89023. newMesh.computeWorldMatrix(true);
  89024. // Apply submeshes
  89025. newMesh.subMeshes = [];
  89026. var index = 0;
  89027. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89028. var meshID = meshes[meshIndex];
  89029. var mesh = gltfRuntime.meshes[meshID];
  89030. if (!mesh) {
  89031. continue;
  89032. }
  89033. for (var i = 0; i < mesh.primitives.length; i++) {
  89034. if (mesh.primitives[i].mode !== 4) {
  89035. //continue;
  89036. }
  89037. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89038. index++;
  89039. }
  89040. }
  89041. // Finish
  89042. return newMesh;
  89043. };
  89044. /**
  89045. * Configure node transformation from position, rotation and scaling
  89046. */
  89047. var configureNode = function (newNode, position, rotation, scaling) {
  89048. if (newNode.position) {
  89049. newNode.position = position;
  89050. }
  89051. if (newNode.rotationQuaternion || newNode.rotation) {
  89052. newNode.rotationQuaternion = rotation;
  89053. }
  89054. if (newNode.scaling) {
  89055. newNode.scaling = scaling;
  89056. }
  89057. };
  89058. /**
  89059. * Configures node from transformation matrix
  89060. */
  89061. var configureNodeFromMatrix = function (newNode, node, parent) {
  89062. if (node.matrix) {
  89063. var position = new BABYLON.Vector3(0, 0, 0);
  89064. var rotation = new BABYLON.Quaternion();
  89065. var scaling = new BABYLON.Vector3(0, 0, 0);
  89066. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89067. mat.decompose(scaling, rotation, position);
  89068. configureNode(newNode, position, rotation, scaling);
  89069. }
  89070. else if (node.translation && node.rotation && node.scale) {
  89071. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89072. }
  89073. newNode.computeWorldMatrix(true);
  89074. };
  89075. /**
  89076. * Imports a node
  89077. */
  89078. var importNode = function (gltfRuntime, node, id, parent) {
  89079. var lastNode = null;
  89080. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89081. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89082. return null;
  89083. }
  89084. }
  89085. // Meshes
  89086. if (node.skin) {
  89087. if (node.meshes) {
  89088. var skin = gltfRuntime.skins[node.skin];
  89089. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89090. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89091. if (newMesh.skeleton === null) {
  89092. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89093. if (!skin.babylonSkeleton) {
  89094. skin.babylonSkeleton = newMesh.skeleton;
  89095. }
  89096. }
  89097. lastNode = newMesh;
  89098. }
  89099. }
  89100. else if (node.meshes) {
  89101. /**
  89102. * Improve meshes property
  89103. */
  89104. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89105. lastNode = newMesh;
  89106. }
  89107. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89108. var light = gltfRuntime.lights[node.light];
  89109. if (light) {
  89110. if (light.type === "ambient") {
  89111. var ambienLight = light[light.type];
  89112. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89113. hemiLight.name = node.name || "";
  89114. if (ambienLight.color) {
  89115. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89116. }
  89117. lastNode = hemiLight;
  89118. }
  89119. else if (light.type === "directional") {
  89120. var directionalLight = light[light.type];
  89121. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89122. dirLight.name = node.name || "";
  89123. if (directionalLight.color) {
  89124. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89125. }
  89126. lastNode = dirLight;
  89127. }
  89128. else if (light.type === "point") {
  89129. var pointLight = light[light.type];
  89130. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89131. ptLight.name = node.name || "";
  89132. if (pointLight.color) {
  89133. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89134. }
  89135. lastNode = ptLight;
  89136. }
  89137. else if (light.type === "spot") {
  89138. var spotLight = light[light.type];
  89139. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89140. spLight.name = node.name || "";
  89141. if (spotLight.color) {
  89142. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89143. }
  89144. if (spotLight.fallOfAngle) {
  89145. spLight.angle = spotLight.fallOfAngle;
  89146. }
  89147. if (spotLight.fallOffExponent) {
  89148. spLight.exponent = spotLight.fallOffExponent;
  89149. }
  89150. lastNode = spLight;
  89151. }
  89152. }
  89153. }
  89154. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89155. var camera = gltfRuntime.cameras[node.camera];
  89156. if (camera) {
  89157. if (camera.type === "orthographic") {
  89158. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89159. orthoCamera.name = node.name || "";
  89160. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89161. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89162. lastNode = orthoCamera;
  89163. }
  89164. else if (camera.type === "perspective") {
  89165. var perspectiveCamera = camera[camera.type];
  89166. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89167. persCamera.name = node.name || "";
  89168. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89169. if (!perspectiveCamera.aspectRatio) {
  89170. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89171. }
  89172. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89173. persCamera.maxZ = perspectiveCamera.zfar;
  89174. persCamera.minZ = perspectiveCamera.znear;
  89175. }
  89176. lastNode = persCamera;
  89177. }
  89178. }
  89179. }
  89180. // Empty node
  89181. if (!node.jointName) {
  89182. if (node.babylonNode) {
  89183. return node.babylonNode;
  89184. }
  89185. else if (lastNode === null) {
  89186. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89187. node.babylonNode = dummy;
  89188. lastNode = dummy;
  89189. }
  89190. }
  89191. if (lastNode !== null) {
  89192. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89193. configureNodeFromMatrix(lastNode, node, parent);
  89194. }
  89195. else {
  89196. var translation = node.translation || [0, 0, 0];
  89197. var rotation = node.rotation || [0, 0, 0, 1];
  89198. var scale = node.scale || [1, 1, 1];
  89199. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89200. }
  89201. lastNode.updateCache(true);
  89202. node.babylonNode = lastNode;
  89203. }
  89204. return lastNode;
  89205. };
  89206. /**
  89207. * Traverses nodes and creates them
  89208. */
  89209. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89210. if (meshIncluded === void 0) { meshIncluded = false; }
  89211. var node = gltfRuntime.nodes[id];
  89212. var newNode = null;
  89213. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89214. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89215. meshIncluded = true;
  89216. }
  89217. else {
  89218. meshIncluded = false;
  89219. }
  89220. }
  89221. else {
  89222. meshIncluded = true;
  89223. }
  89224. if (!node.jointName && meshIncluded) {
  89225. newNode = importNode(gltfRuntime, node, id, parent);
  89226. if (newNode !== null) {
  89227. newNode.id = id;
  89228. newNode.parent = parent;
  89229. }
  89230. }
  89231. if (node.children) {
  89232. for (var i = 0; i < node.children.length; i++) {
  89233. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89234. }
  89235. }
  89236. };
  89237. /**
  89238. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89239. */
  89240. var postLoad = function (gltfRuntime) {
  89241. // Nodes
  89242. var currentScene = gltfRuntime.currentScene;
  89243. if (currentScene) {
  89244. for (var i = 0; i < currentScene.nodes.length; i++) {
  89245. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89246. }
  89247. }
  89248. else {
  89249. for (var thing in gltfRuntime.scenes) {
  89250. currentScene = gltfRuntime.scenes[thing];
  89251. for (var i = 0; i < currentScene.nodes.length; i++) {
  89252. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89253. }
  89254. }
  89255. }
  89256. // Set animations
  89257. loadAnimations(gltfRuntime);
  89258. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89259. var skeleton = gltfRuntime.scene.skeletons[i];
  89260. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89261. }
  89262. };
  89263. /**
  89264. * onBind shaderrs callback to set uniforms and matrices
  89265. */
  89266. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89267. var materialValues = material.values || technique.parameters;
  89268. for (var unif in unTreatedUniforms) {
  89269. var uniform = unTreatedUniforms[unif];
  89270. var type = uniform.type;
  89271. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89272. if (uniform.semantic && !uniform.source && !uniform.node) {
  89273. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89274. }
  89275. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89276. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89277. if (source === null) {
  89278. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89279. }
  89280. if (source === null) {
  89281. continue;
  89282. }
  89283. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89284. }
  89285. }
  89286. else {
  89287. var value = materialValues[technique.uniforms[unif]];
  89288. if (!value) {
  89289. continue;
  89290. }
  89291. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89292. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89293. if (texture === null || texture === undefined) {
  89294. continue;
  89295. }
  89296. shaderMaterial.getEffect().setTexture(unif, texture);
  89297. }
  89298. else {
  89299. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89300. }
  89301. }
  89302. }
  89303. onSuccess(shaderMaterial);
  89304. };
  89305. /**
  89306. * Prepare uniforms to send the only one time
  89307. * Loads the appropriate textures
  89308. */
  89309. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89310. var materialValues = material.values || technique.parameters;
  89311. var techniqueUniforms = technique.uniforms;
  89312. /**
  89313. * Prepare values here (not matrices)
  89314. */
  89315. for (var unif in unTreatedUniforms) {
  89316. var uniform = unTreatedUniforms[unif];
  89317. var type = uniform.type;
  89318. var value = materialValues[techniqueUniforms[unif]];
  89319. if (value === undefined) {
  89320. // In case the value is the same for all materials
  89321. value = uniform.value;
  89322. }
  89323. if (!value) {
  89324. continue;
  89325. }
  89326. var onLoadTexture = function (uniformName) {
  89327. return function (texture) {
  89328. if (uniform.value && uniformName) {
  89329. // Static uniform
  89330. shaderMaterial.setTexture(uniformName, texture);
  89331. delete unTreatedUniforms[uniformName];
  89332. }
  89333. };
  89334. };
  89335. // Texture (sampler2D)
  89336. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89337. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89338. }
  89339. else {
  89340. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89341. // Static uniform
  89342. delete unTreatedUniforms[unif];
  89343. }
  89344. }
  89345. }
  89346. };
  89347. /**
  89348. * Shader compilation failed
  89349. */
  89350. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89351. return function (effect, error) {
  89352. shaderMaterial.dispose(true);
  89353. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89354. };
  89355. };
  89356. /**
  89357. * Shader compilation success
  89358. */
  89359. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89360. return function (_) {
  89361. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89362. shaderMaterial.onBind = function (mesh) {
  89363. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89364. };
  89365. };
  89366. };
  89367. /**
  89368. * Returns the appropriate uniform if already handled by babylon
  89369. */
  89370. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89371. for (var unif in technique.uniforms) {
  89372. var uniform = technique.uniforms[unif];
  89373. var uniformParameter = technique.parameters[uniform];
  89374. if (tokenizer.currentIdentifier === unif) {
  89375. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89376. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89377. if (transformIndex !== -1) {
  89378. delete unTreatedUniforms[unif];
  89379. return babylonTransforms[transformIndex];
  89380. }
  89381. }
  89382. }
  89383. }
  89384. return tokenizer.currentIdentifier;
  89385. };
  89386. /**
  89387. * All shaders loaded. Create materials one by one
  89388. */
  89389. var importMaterials = function (gltfRuntime) {
  89390. // Create materials
  89391. for (var mat in gltfRuntime.materials) {
  89392. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89393. }
  89394. };
  89395. /**
  89396. * Implementation of the base glTF spec
  89397. */
  89398. var GLTFLoaderBase = /** @class */ (function () {
  89399. function GLTFLoaderBase() {
  89400. }
  89401. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89402. var gltfRuntime = {
  89403. extensions: {},
  89404. accessors: {},
  89405. buffers: {},
  89406. bufferViews: {},
  89407. meshes: {},
  89408. lights: {},
  89409. cameras: {},
  89410. nodes: {},
  89411. images: {},
  89412. textures: {},
  89413. shaders: {},
  89414. programs: {},
  89415. samplers: {},
  89416. techniques: {},
  89417. materials: {},
  89418. animations: {},
  89419. skins: {},
  89420. extensionsUsed: [],
  89421. scenes: {},
  89422. buffersCount: 0,
  89423. shaderscount: 0,
  89424. scene: scene,
  89425. rootUrl: rootUrl,
  89426. loadedBufferCount: 0,
  89427. loadedBufferViews: {},
  89428. loadedShaderCount: 0,
  89429. importOnlyMeshes: false,
  89430. dummyNodes: []
  89431. };
  89432. // Parse
  89433. if (parsedData.extensions) {
  89434. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89435. }
  89436. if (parsedData.extensionsUsed) {
  89437. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89438. }
  89439. if (parsedData.buffers) {
  89440. parseBuffers(parsedData.buffers, gltfRuntime);
  89441. }
  89442. if (parsedData.bufferViews) {
  89443. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89444. }
  89445. if (parsedData.accessors) {
  89446. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89447. }
  89448. if (parsedData.meshes) {
  89449. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89450. }
  89451. if (parsedData.lights) {
  89452. parseObject(parsedData.lights, "lights", gltfRuntime);
  89453. }
  89454. if (parsedData.cameras) {
  89455. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89456. }
  89457. if (parsedData.nodes) {
  89458. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89459. }
  89460. if (parsedData.images) {
  89461. parseObject(parsedData.images, "images", gltfRuntime);
  89462. }
  89463. if (parsedData.textures) {
  89464. parseObject(parsedData.textures, "textures", gltfRuntime);
  89465. }
  89466. if (parsedData.shaders) {
  89467. parseShaders(parsedData.shaders, gltfRuntime);
  89468. }
  89469. if (parsedData.programs) {
  89470. parseObject(parsedData.programs, "programs", gltfRuntime);
  89471. }
  89472. if (parsedData.samplers) {
  89473. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89474. }
  89475. if (parsedData.techniques) {
  89476. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89477. }
  89478. if (parsedData.materials) {
  89479. parseObject(parsedData.materials, "materials", gltfRuntime);
  89480. }
  89481. if (parsedData.animations) {
  89482. parseObject(parsedData.animations, "animations", gltfRuntime);
  89483. }
  89484. if (parsedData.skins) {
  89485. parseObject(parsedData.skins, "skins", gltfRuntime);
  89486. }
  89487. if (parsedData.scenes) {
  89488. gltfRuntime.scenes = parsedData.scenes;
  89489. }
  89490. if (parsedData.scene && parsedData.scenes) {
  89491. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89492. }
  89493. return gltfRuntime;
  89494. };
  89495. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89496. var buffer = gltfRuntime.buffers[id];
  89497. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89498. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89499. }
  89500. else {
  89501. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89502. if (request) {
  89503. onError(request.status + " " + request.statusText);
  89504. }
  89505. });
  89506. }
  89507. };
  89508. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89509. var texture = gltfRuntime.textures[id];
  89510. if (!texture || !texture.source) {
  89511. onError("");
  89512. return;
  89513. }
  89514. if (texture.babylonTexture) {
  89515. onSuccess(null);
  89516. return;
  89517. }
  89518. var source = gltfRuntime.images[texture.source];
  89519. if (BABYLON.Tools.IsBase64(source.uri)) {
  89520. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89521. }
  89522. else {
  89523. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89524. if (request) {
  89525. onError(request.status + " " + request.statusText);
  89526. }
  89527. });
  89528. }
  89529. };
  89530. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89531. var texture = gltfRuntime.textures[id];
  89532. if (texture.babylonTexture) {
  89533. onSuccess(texture.babylonTexture);
  89534. return;
  89535. }
  89536. var sampler = gltfRuntime.samplers[texture.sampler];
  89537. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89538. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89539. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89540. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89541. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89542. var blob = new Blob([buffer]);
  89543. var blobURL = URL.createObjectURL(blob);
  89544. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89545. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89546. if (sampler.wrapS !== undefined) {
  89547. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89548. }
  89549. if (sampler.wrapT !== undefined) {
  89550. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89551. }
  89552. newTexture.name = id;
  89553. texture.babylonTexture = newTexture;
  89554. onSuccess(newTexture);
  89555. };
  89556. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89557. var shader = gltfRuntime.shaders[id];
  89558. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89559. var shaderString = atob(shader.uri.split(",")[1]);
  89560. onSuccess(shaderString);
  89561. }
  89562. else {
  89563. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89564. if (request) {
  89565. onError(request.status + " " + request.statusText);
  89566. }
  89567. });
  89568. }
  89569. };
  89570. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89571. var material = gltfRuntime.materials[id];
  89572. if (!material.technique) {
  89573. if (onError) {
  89574. onError("No technique found.");
  89575. }
  89576. return;
  89577. }
  89578. var technique = gltfRuntime.techniques[material.technique];
  89579. if (!technique) {
  89580. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89581. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89582. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89583. onSuccess(defaultMaterial);
  89584. return;
  89585. }
  89586. var program = gltfRuntime.programs[technique.program];
  89587. var states = technique.states;
  89588. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89589. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89590. var newVertexShader = "";
  89591. var newPixelShader = "";
  89592. var vertexTokenizer = new Tokenizer(vertexShader);
  89593. var pixelTokenizer = new Tokenizer(pixelShader);
  89594. var unTreatedUniforms = {};
  89595. var uniforms = [];
  89596. var attributes = [];
  89597. var samplers = [];
  89598. // Fill uniform, sampler2D and attributes
  89599. for (var unif in technique.uniforms) {
  89600. var uniform = technique.uniforms[unif];
  89601. var uniformParameter = technique.parameters[uniform];
  89602. unTreatedUniforms[unif] = uniformParameter;
  89603. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89604. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89605. if (transformIndex !== -1) {
  89606. uniforms.push(babylonTransforms[transformIndex]);
  89607. delete unTreatedUniforms[unif];
  89608. }
  89609. else {
  89610. uniforms.push(unif);
  89611. }
  89612. }
  89613. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89614. samplers.push(unif);
  89615. }
  89616. else {
  89617. uniforms.push(unif);
  89618. }
  89619. }
  89620. for (var attr in technique.attributes) {
  89621. var attribute = technique.attributes[attr];
  89622. var attributeParameter = technique.parameters[attribute];
  89623. if (attributeParameter.semantic) {
  89624. attributes.push(getAttribute(attributeParameter));
  89625. }
  89626. }
  89627. // Configure vertex shader
  89628. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89629. var tokenType = vertexTokenizer.currentToken;
  89630. if (tokenType !== ETokenType.IDENTIFIER) {
  89631. newVertexShader += vertexTokenizer.currentString;
  89632. continue;
  89633. }
  89634. var foundAttribute = false;
  89635. for (var attr in technique.attributes) {
  89636. var attribute = technique.attributes[attr];
  89637. var attributeParameter = technique.parameters[attribute];
  89638. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89639. newVertexShader += getAttribute(attributeParameter);
  89640. foundAttribute = true;
  89641. break;
  89642. }
  89643. }
  89644. if (foundAttribute) {
  89645. continue;
  89646. }
  89647. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89648. }
  89649. // Configure pixel shader
  89650. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89651. var tokenType = pixelTokenizer.currentToken;
  89652. if (tokenType !== ETokenType.IDENTIFIER) {
  89653. newPixelShader += pixelTokenizer.currentString;
  89654. continue;
  89655. }
  89656. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89657. }
  89658. // Create shader material
  89659. var shaderPath = {
  89660. vertex: program.vertexShader + id,
  89661. fragment: program.fragmentShader + id
  89662. };
  89663. var options = {
  89664. attributes: attributes,
  89665. uniforms: uniforms,
  89666. samplers: samplers,
  89667. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89668. };
  89669. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89670. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89671. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89672. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89673. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89674. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89675. if (states && states.functions) {
  89676. var functions = states.functions;
  89677. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89678. shaderMaterial.backFaceCulling = false;
  89679. }
  89680. var blendFunc = functions.blendFuncSeparate;
  89681. if (blendFunc) {
  89682. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89683. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89684. }
  89685. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89686. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89687. }
  89688. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89689. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89690. }
  89691. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89692. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89693. }
  89694. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89695. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89696. }
  89697. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89698. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89699. }
  89700. }
  89701. }
  89702. };
  89703. return GLTFLoaderBase;
  89704. }());
  89705. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89706. /**
  89707. * glTF V1 Loader
  89708. */
  89709. var GLTFLoader = /** @class */ (function () {
  89710. function GLTFLoader() {
  89711. // #region Stubs for IGLTFLoader interface
  89712. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89713. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89714. this.compileMaterials = false;
  89715. this.useClipPlane = false;
  89716. this.compileShadowGenerators = false;
  89717. this.onDisposeObservable = new BABYLON.Observable();
  89718. this.onMeshLoadedObservable = new BABYLON.Observable();
  89719. this.onTextureLoadedObservable = new BABYLON.Observable();
  89720. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89721. this.onCompleteObservable = new BABYLON.Observable();
  89722. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89723. this.state = null;
  89724. }
  89725. GLTFLoader.RegisterExtension = function (extension) {
  89726. if (GLTFLoader.Extensions[extension.name]) {
  89727. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89728. return;
  89729. }
  89730. GLTFLoader.Extensions[extension.name] = extension;
  89731. };
  89732. GLTFLoader.prototype.dispose = function () { };
  89733. // #endregion
  89734. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89735. var _this = this;
  89736. scene.useRightHandedSystem = true;
  89737. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89738. gltfRuntime.importOnlyMeshes = true;
  89739. if (meshesNames === "") {
  89740. gltfRuntime.importMeshesNames = [];
  89741. }
  89742. else if (typeof meshesNames === "string") {
  89743. gltfRuntime.importMeshesNames = [meshesNames];
  89744. }
  89745. else if (meshesNames && !(meshesNames instanceof Array)) {
  89746. gltfRuntime.importMeshesNames = [meshesNames];
  89747. }
  89748. else {
  89749. gltfRuntime.importMeshesNames = [];
  89750. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  89751. }
  89752. // Create nodes
  89753. _this._createNodes(gltfRuntime);
  89754. var meshes = new Array();
  89755. var skeletons = new Array();
  89756. // Fill arrays of meshes and skeletons
  89757. for (var nde in gltfRuntime.nodes) {
  89758. var node = gltfRuntime.nodes[nde];
  89759. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  89760. meshes.push(node.babylonNode);
  89761. }
  89762. }
  89763. for (var skl in gltfRuntime.skins) {
  89764. var skin = gltfRuntime.skins[skl];
  89765. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  89766. skeletons.push(skin.babylonSkeleton);
  89767. }
  89768. }
  89769. // Load buffers, shaders, materials, etc.
  89770. _this._loadBuffersAsync(gltfRuntime, function () {
  89771. _this._loadShadersAsync(gltfRuntime, function () {
  89772. importMaterials(gltfRuntime);
  89773. postLoad(gltfRuntime);
  89774. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89775. onSuccess(meshes, [], skeletons);
  89776. }
  89777. });
  89778. }, onProgress);
  89779. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89780. onSuccess(meshes, [], skeletons);
  89781. }
  89782. }, onError);
  89783. return true;
  89784. };
  89785. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89786. var _this = this;
  89787. return new Promise(function (resolve, reject) {
  89788. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  89789. resolve({
  89790. meshes: meshes,
  89791. particleSystems: particleSystems,
  89792. skeletons: skeletons
  89793. });
  89794. }, onProgress, function (message) {
  89795. reject(new Error(message));
  89796. });
  89797. });
  89798. };
  89799. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89800. var _this = this;
  89801. scene.useRightHandedSystem = true;
  89802. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89803. // Load runtime extensios
  89804. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  89805. // Create nodes
  89806. _this._createNodes(gltfRuntime);
  89807. // Load buffers, shaders, materials, etc.
  89808. _this._loadBuffersAsync(gltfRuntime, function () {
  89809. _this._loadShadersAsync(gltfRuntime, function () {
  89810. importMaterials(gltfRuntime);
  89811. postLoad(gltfRuntime);
  89812. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  89813. onSuccess();
  89814. }
  89815. });
  89816. });
  89817. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  89818. onSuccess();
  89819. }
  89820. }, onError);
  89821. }, onError);
  89822. };
  89823. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89824. var _this = this;
  89825. return new Promise(function (resolve, reject) {
  89826. _this._loadAsync(scene, data, rootUrl, function () {
  89827. resolve();
  89828. }, onProgress, function (message) {
  89829. reject(new Error(message));
  89830. });
  89831. });
  89832. };
  89833. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  89834. var hasShaders = false;
  89835. var processShader = function (sha, shader) {
  89836. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  89837. gltfRuntime.loadedShaderCount++;
  89838. if (shaderString) {
  89839. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  89840. }
  89841. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  89842. onload();
  89843. }
  89844. }, function () {
  89845. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  89846. });
  89847. };
  89848. for (var sha in gltfRuntime.shaders) {
  89849. hasShaders = true;
  89850. var shader = gltfRuntime.shaders[sha];
  89851. if (shader) {
  89852. processShader.bind(this, sha, shader)();
  89853. }
  89854. else {
  89855. BABYLON.Tools.Error("No shader named: " + sha);
  89856. }
  89857. }
  89858. if (!hasShaders) {
  89859. onload();
  89860. }
  89861. };
  89862. ;
  89863. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  89864. var hasBuffers = false;
  89865. var processBuffer = function (buf, buffer) {
  89866. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  89867. gltfRuntime.loadedBufferCount++;
  89868. if (bufferView) {
  89869. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  89870. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  89871. }
  89872. gltfRuntime.loadedBufferViews[buf] = bufferView;
  89873. }
  89874. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  89875. onLoad();
  89876. }
  89877. }, function () {
  89878. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  89879. });
  89880. };
  89881. for (var buf in gltfRuntime.buffers) {
  89882. hasBuffers = true;
  89883. var buffer = gltfRuntime.buffers[buf];
  89884. if (buffer) {
  89885. processBuffer.bind(this, buf, buffer)();
  89886. }
  89887. else {
  89888. BABYLON.Tools.Error("No buffer named: " + buf);
  89889. }
  89890. }
  89891. if (!hasBuffers) {
  89892. onLoad();
  89893. }
  89894. };
  89895. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  89896. var currentScene = gltfRuntime.currentScene;
  89897. if (currentScene) {
  89898. // Only one scene even if multiple scenes are defined
  89899. for (var i = 0; i < currentScene.nodes.length; i++) {
  89900. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89901. }
  89902. }
  89903. else {
  89904. // Load all scenes
  89905. for (var thing in gltfRuntime.scenes) {
  89906. currentScene = gltfRuntime.scenes[thing];
  89907. for (var i = 0; i < currentScene.nodes.length; i++) {
  89908. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89909. }
  89910. }
  89911. }
  89912. };
  89913. GLTFLoader.Extensions = {};
  89914. return GLTFLoader;
  89915. }());
  89916. GLTF1.GLTFLoader = GLTFLoader;
  89917. ;
  89918. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  89919. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89920. })(BABYLON || (BABYLON = {}));
  89921. //# sourceMappingURL=babylon.glTFLoader.js.map
  89922. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89923. var BABYLON;
  89924. (function (BABYLON) {
  89925. var GLTF1;
  89926. (function (GLTF1) {
  89927. /**
  89928. * Utils functions for GLTF
  89929. */
  89930. var GLTFUtils = /** @class */ (function () {
  89931. function GLTFUtils() {
  89932. }
  89933. /**
  89934. * Sets the given "parameter" matrix
  89935. * @param scene: the {BABYLON.Scene} object
  89936. * @param source: the source node where to pick the matrix
  89937. * @param parameter: the GLTF technique parameter
  89938. * @param uniformName: the name of the shader's uniform
  89939. * @param shaderMaterial: the shader material
  89940. */
  89941. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  89942. var mat = null;
  89943. if (parameter.semantic === "MODEL") {
  89944. mat = source.getWorldMatrix();
  89945. }
  89946. else if (parameter.semantic === "PROJECTION") {
  89947. mat = scene.getProjectionMatrix();
  89948. }
  89949. else if (parameter.semantic === "VIEW") {
  89950. mat = scene.getViewMatrix();
  89951. }
  89952. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  89953. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  89954. }
  89955. else if (parameter.semantic === "MODELVIEW") {
  89956. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  89957. }
  89958. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  89959. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  89960. }
  89961. else if (parameter.semantic === "MODELINVERSE") {
  89962. mat = source.getWorldMatrix().invert();
  89963. }
  89964. else if (parameter.semantic === "VIEWINVERSE") {
  89965. mat = scene.getViewMatrix().invert();
  89966. }
  89967. else if (parameter.semantic === "PROJECTIONINVERSE") {
  89968. mat = scene.getProjectionMatrix().invert();
  89969. }
  89970. else if (parameter.semantic === "MODELVIEWINVERSE") {
  89971. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  89972. }
  89973. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  89974. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  89975. }
  89976. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  89977. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  89978. }
  89979. else {
  89980. debugger;
  89981. }
  89982. if (mat) {
  89983. switch (parameter.type) {
  89984. case GLTF1.EParameterType.FLOAT_MAT2:
  89985. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  89986. break;
  89987. case GLTF1.EParameterType.FLOAT_MAT3:
  89988. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  89989. break;
  89990. case GLTF1.EParameterType.FLOAT_MAT4:
  89991. shaderMaterial.setMatrix(uniformName, mat);
  89992. break;
  89993. default: break;
  89994. }
  89995. }
  89996. };
  89997. /**
  89998. * Sets the given "parameter" matrix
  89999. * @param shaderMaterial: the shader material
  90000. * @param uniform: the name of the shader's uniform
  90001. * @param value: the value of the uniform
  90002. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90003. */
  90004. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90005. switch (type) {
  90006. case GLTF1.EParameterType.FLOAT:
  90007. shaderMaterial.setFloat(uniform, value);
  90008. return true;
  90009. case GLTF1.EParameterType.FLOAT_VEC2:
  90010. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90011. return true;
  90012. case GLTF1.EParameterType.FLOAT_VEC3:
  90013. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90014. return true;
  90015. case GLTF1.EParameterType.FLOAT_VEC4:
  90016. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90017. return true;
  90018. default: return false;
  90019. }
  90020. };
  90021. /**
  90022. * Returns the wrap mode of the texture
  90023. * @param mode: the mode value
  90024. */
  90025. GLTFUtils.GetWrapMode = function (mode) {
  90026. switch (mode) {
  90027. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90028. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90029. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90030. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90031. }
  90032. };
  90033. /**
  90034. * Returns the byte stride giving an accessor
  90035. * @param accessor: the GLTF accessor objet
  90036. */
  90037. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90038. // Needs this function since "byteStride" isn't requiered in glTF format
  90039. var type = accessor.type;
  90040. switch (type) {
  90041. case "VEC2": return 2;
  90042. case "VEC3": return 3;
  90043. case "VEC4": return 4;
  90044. case "MAT2": return 4;
  90045. case "MAT3": return 9;
  90046. case "MAT4": return 16;
  90047. default: return 1;
  90048. }
  90049. };
  90050. /**
  90051. * Returns the texture filter mode giving a mode value
  90052. * @param mode: the filter mode value
  90053. */
  90054. GLTFUtils.GetTextureFilterMode = function (mode) {
  90055. switch (mode) {
  90056. case GLTF1.ETextureFilterType.LINEAR:
  90057. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90058. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90059. case GLTF1.ETextureFilterType.NEAREST:
  90060. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90061. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90062. }
  90063. };
  90064. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90065. var byteOffset = bufferView.byteOffset + byteOffset;
  90066. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90067. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90068. throw new Error("Buffer access is out of range");
  90069. }
  90070. var buffer = loadedBufferView.buffer;
  90071. byteOffset += loadedBufferView.byteOffset;
  90072. switch (componentType) {
  90073. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90074. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90075. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90076. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90077. default: return new Float32Array(buffer, byteOffset, byteLength);
  90078. }
  90079. };
  90080. /**
  90081. * Returns a buffer from its accessor
  90082. * @param gltfRuntime: the GLTF runtime
  90083. * @param accessor: the GLTF accessor
  90084. */
  90085. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90086. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90087. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90088. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90089. };
  90090. /**
  90091. * Decodes a buffer view into a string
  90092. * @param view: the buffer view
  90093. */
  90094. GLTFUtils.DecodeBufferToText = function (view) {
  90095. var result = "";
  90096. var length = view.byteLength;
  90097. for (var i = 0; i < length; ++i) {
  90098. result += String.fromCharCode(view[i]);
  90099. }
  90100. return result;
  90101. };
  90102. /**
  90103. * Returns the default material of gltf. Related to
  90104. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90105. * @param scene: the Babylon.js scene
  90106. */
  90107. GLTFUtils.GetDefaultMaterial = function (scene) {
  90108. if (!GLTFUtils._DefaultMaterial) {
  90109. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90110. "precision highp float;",
  90111. "",
  90112. "uniform mat4 worldView;",
  90113. "uniform mat4 projection;",
  90114. "",
  90115. "attribute vec3 position;",
  90116. "",
  90117. "void main(void)",
  90118. "{",
  90119. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90120. "}"
  90121. ].join("\n");
  90122. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90123. "precision highp float;",
  90124. "",
  90125. "uniform vec4 u_emission;",
  90126. "",
  90127. "void main(void)",
  90128. "{",
  90129. " gl_FragColor = u_emission;",
  90130. "}"
  90131. ].join("\n");
  90132. var shaderPath = {
  90133. vertex: "GLTFDefaultMaterial",
  90134. fragment: "GLTFDefaultMaterial"
  90135. };
  90136. var options = {
  90137. attributes: ["position"],
  90138. uniforms: ["worldView", "projection", "u_emission"],
  90139. samplers: new Array(),
  90140. needAlphaBlending: false
  90141. };
  90142. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90143. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90144. }
  90145. return GLTFUtils._DefaultMaterial;
  90146. };
  90147. // The GLTF default material
  90148. GLTFUtils._DefaultMaterial = null;
  90149. return GLTFUtils;
  90150. }());
  90151. GLTF1.GLTFUtils = GLTFUtils;
  90152. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90153. })(BABYLON || (BABYLON = {}));
  90154. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90155. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90156. var BABYLON;
  90157. (function (BABYLON) {
  90158. var GLTF1;
  90159. (function (GLTF1) {
  90160. var GLTFLoaderExtension = /** @class */ (function () {
  90161. function GLTFLoaderExtension(name) {
  90162. this._name = name;
  90163. }
  90164. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90165. get: function () {
  90166. return this._name;
  90167. },
  90168. enumerable: true,
  90169. configurable: true
  90170. });
  90171. /**
  90172. * Defines an override for loading the runtime
  90173. * Return true to stop further extensions from loading the runtime
  90174. */
  90175. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90176. return false;
  90177. };
  90178. /**
  90179. * Defines an onverride for creating gltf runtime
  90180. * Return true to stop further extensions from creating the runtime
  90181. */
  90182. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90183. return false;
  90184. };
  90185. /**
  90186. * Defines an override for loading buffers
  90187. * Return true to stop further extensions from loading this buffer
  90188. */
  90189. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90190. return false;
  90191. };
  90192. /**
  90193. * Defines an override for loading texture buffers
  90194. * Return true to stop further extensions from loading this texture data
  90195. */
  90196. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90197. return false;
  90198. };
  90199. /**
  90200. * Defines an override for creating textures
  90201. * Return true to stop further extensions from loading this texture
  90202. */
  90203. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90204. return false;
  90205. };
  90206. /**
  90207. * Defines an override for loading shader strings
  90208. * Return true to stop further extensions from loading this shader data
  90209. */
  90210. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90211. return false;
  90212. };
  90213. /**
  90214. * Defines an override for loading materials
  90215. * Return true to stop further extensions from loading this material
  90216. */
  90217. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90218. return false;
  90219. };
  90220. // ---------
  90221. // Utilities
  90222. // ---------
  90223. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90224. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90225. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90226. }, function () {
  90227. setTimeout(function () {
  90228. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90229. });
  90230. });
  90231. };
  90232. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90233. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90234. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90235. }, function () {
  90236. setTimeout(function () {
  90237. onSuccess();
  90238. });
  90239. });
  90240. };
  90241. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90242. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90243. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90244. }, function () {
  90245. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90246. });
  90247. };
  90248. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90249. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90250. };
  90251. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90252. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90253. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90254. }, function () {
  90255. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90256. });
  90257. };
  90258. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90259. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90260. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90261. }, function () {
  90262. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90263. });
  90264. };
  90265. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90266. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90267. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90268. }, function () {
  90269. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90270. });
  90271. };
  90272. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90273. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90274. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90275. }, function () {
  90276. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90277. });
  90278. };
  90279. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90280. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90281. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90282. if (func(loaderExtension)) {
  90283. return;
  90284. }
  90285. }
  90286. defaultFunc();
  90287. };
  90288. return GLTFLoaderExtension;
  90289. }());
  90290. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90291. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90292. })(BABYLON || (BABYLON = {}));
  90293. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90294. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90295. var BABYLON;
  90296. (function (BABYLON) {
  90297. var GLTF1;
  90298. (function (GLTF1) {
  90299. var BinaryExtensionBufferName = "binary_glTF";
  90300. ;
  90301. ;
  90302. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90303. __extends(GLTFBinaryExtension, _super);
  90304. function GLTFBinaryExtension() {
  90305. return _super.call(this, "KHR_binary_glTF") || this;
  90306. }
  90307. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90308. var extensionsUsed = data.json.extensionsUsed;
  90309. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90310. return false;
  90311. }
  90312. this._bin = data.bin;
  90313. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90314. return true;
  90315. };
  90316. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90317. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90318. return false;
  90319. }
  90320. if (id !== BinaryExtensionBufferName) {
  90321. return false;
  90322. }
  90323. onSuccess(this._bin);
  90324. return true;
  90325. };
  90326. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90327. var texture = gltfRuntime.textures[id];
  90328. var source = gltfRuntime.images[texture.source];
  90329. if (!source.extensions || !(this.name in source.extensions)) {
  90330. return false;
  90331. }
  90332. var sourceExt = source.extensions[this.name];
  90333. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90334. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90335. onSuccess(buffer);
  90336. return true;
  90337. };
  90338. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90339. var shader = gltfRuntime.shaders[id];
  90340. if (!shader.extensions || !(this.name in shader.extensions)) {
  90341. return false;
  90342. }
  90343. var binaryExtensionShader = shader.extensions[this.name];
  90344. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90345. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90346. setTimeout(function () {
  90347. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90348. onSuccess(shaderString);
  90349. });
  90350. return true;
  90351. };
  90352. return GLTFBinaryExtension;
  90353. }(GLTF1.GLTFLoaderExtension));
  90354. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90355. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90356. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90357. })(BABYLON || (BABYLON = {}));
  90358. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90359. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90360. var BABYLON;
  90361. (function (BABYLON) {
  90362. var GLTF1;
  90363. (function (GLTF1) {
  90364. ;
  90365. ;
  90366. ;
  90367. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90368. __extends(GLTFMaterialsCommonExtension, _super);
  90369. function GLTFMaterialsCommonExtension() {
  90370. return _super.call(this, "KHR_materials_common") || this;
  90371. }
  90372. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90373. if (!gltfRuntime.extensions)
  90374. return false;
  90375. var extension = gltfRuntime.extensions[this.name];
  90376. if (!extension)
  90377. return false;
  90378. // Create lights
  90379. var lights = extension.lights;
  90380. if (lights) {
  90381. for (var thing in lights) {
  90382. var light = lights[thing];
  90383. switch (light.type) {
  90384. case "ambient":
  90385. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90386. var ambient = light.ambient;
  90387. if (ambient) {
  90388. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90389. }
  90390. break;
  90391. case "point":
  90392. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90393. var point = light.point;
  90394. if (point) {
  90395. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90396. }
  90397. break;
  90398. case "directional":
  90399. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90400. var directional = light.directional;
  90401. if (directional) {
  90402. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90403. }
  90404. break;
  90405. case "spot":
  90406. var spot = light.spot;
  90407. if (spot) {
  90408. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  90409. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90410. }
  90411. break;
  90412. default:
  90413. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90414. break;
  90415. }
  90416. }
  90417. }
  90418. return false;
  90419. };
  90420. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90421. var material = gltfRuntime.materials[id];
  90422. if (!material || !material.extensions)
  90423. return false;
  90424. var extension = material.extensions[this.name];
  90425. if (!extension)
  90426. return false;
  90427. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90428. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90429. if (extension.technique === "CONSTANT") {
  90430. standardMaterial.disableLighting = true;
  90431. }
  90432. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90433. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90434. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90435. // Ambient
  90436. if (typeof extension.values.ambient === "string") {
  90437. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90438. }
  90439. else {
  90440. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90441. }
  90442. // Diffuse
  90443. if (typeof extension.values.diffuse === "string") {
  90444. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90445. }
  90446. else {
  90447. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90448. }
  90449. // Emission
  90450. if (typeof extension.values.emission === "string") {
  90451. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90452. }
  90453. else {
  90454. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90455. }
  90456. // Specular
  90457. if (typeof extension.values.specular === "string") {
  90458. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90459. }
  90460. else {
  90461. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90462. }
  90463. return true;
  90464. };
  90465. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90466. // Create buffer from texture url
  90467. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90468. // Create texture from buffer
  90469. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90470. }, onError);
  90471. };
  90472. return GLTFMaterialsCommonExtension;
  90473. }(GLTF1.GLTFLoaderExtension));
  90474. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90475. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90476. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90477. })(BABYLON || (BABYLON = {}));
  90478. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90479. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90480. var BABYLON;
  90481. (function (BABYLON) {
  90482. var GLTF2;
  90483. (function (GLTF2) {
  90484. var ArrayItem = /** @class */ (function () {
  90485. function ArrayItem() {
  90486. }
  90487. ArrayItem.Assign = function (values) {
  90488. if (values) {
  90489. for (var index = 0; index < values.length; index++) {
  90490. values[index]._index = index;
  90491. }
  90492. }
  90493. };
  90494. return ArrayItem;
  90495. }());
  90496. GLTF2.ArrayItem = ArrayItem;
  90497. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90498. })(BABYLON || (BABYLON = {}));
  90499. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90500. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90501. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90502. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90503. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90504. var BABYLON;
  90505. (function (BABYLON) {
  90506. var GLTF2;
  90507. (function (GLTF2) {
  90508. var GLTFLoader = /** @class */ (function () {
  90509. function GLTFLoader() {
  90510. this._completePromises = new Array();
  90511. this._disposed = false;
  90512. this._state = null;
  90513. this._extensions = {};
  90514. this._defaultSampler = {};
  90515. this._requests = new Array();
  90516. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90517. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90518. this.compileMaterials = false;
  90519. this.useClipPlane = false;
  90520. this.compileShadowGenerators = false;
  90521. this.onDisposeObservable = new BABYLON.Observable();
  90522. this.onMeshLoadedObservable = new BABYLON.Observable();
  90523. this.onTextureLoadedObservable = new BABYLON.Observable();
  90524. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90525. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90526. this.onCompleteObservable = new BABYLON.Observable();
  90527. }
  90528. GLTFLoader._Register = function (name, factory) {
  90529. if (GLTFLoader._Factories[name]) {
  90530. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90531. return;
  90532. }
  90533. GLTFLoader._Factories[name] = factory;
  90534. // Keep the order of registration so that extensions registered first are called first.
  90535. GLTFLoader._Names.push(name);
  90536. };
  90537. Object.defineProperty(GLTFLoader.prototype, "state", {
  90538. get: function () {
  90539. return this._state;
  90540. },
  90541. enumerable: true,
  90542. configurable: true
  90543. });
  90544. GLTFLoader.prototype.dispose = function () {
  90545. if (this._disposed) {
  90546. return;
  90547. }
  90548. this._disposed = true;
  90549. this.onDisposeObservable.notifyObservers(this);
  90550. this.onDisposeObservable.clear();
  90551. this._clear();
  90552. };
  90553. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90554. var _this = this;
  90555. return Promise.resolve().then(function () {
  90556. var nodes = null;
  90557. if (meshesNames) {
  90558. var nodeMap_1 = {};
  90559. if (_this._gltf.nodes) {
  90560. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90561. var node = _a[_i];
  90562. if (node.name) {
  90563. nodeMap_1[node.name] = node;
  90564. }
  90565. }
  90566. }
  90567. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90568. nodes = names.map(function (name) {
  90569. var node = nodeMap_1[name];
  90570. if (!node) {
  90571. throw new Error("Failed to find node " + name);
  90572. }
  90573. return node;
  90574. });
  90575. }
  90576. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90577. return {
  90578. meshes: _this._getMeshes(),
  90579. particleSystems: [],
  90580. skeletons: _this._getSkeletons(),
  90581. };
  90582. });
  90583. });
  90584. };
  90585. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90586. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90587. };
  90588. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90589. var _this = this;
  90590. return Promise.resolve().then(function () {
  90591. _this._loadExtensions();
  90592. _this._babylonScene = scene;
  90593. _this._rootUrl = rootUrl;
  90594. _this._progressCallback = onProgress;
  90595. _this._state = BABYLON.GLTFLoaderState.Loading;
  90596. _this._loadData(data);
  90597. var promises = new Array();
  90598. if (nodes) {
  90599. promises.push(_this._loadNodesAsync(nodes));
  90600. }
  90601. else {
  90602. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90603. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90604. }
  90605. if (_this.compileMaterials) {
  90606. promises.push(_this._compileMaterialsAsync());
  90607. }
  90608. if (_this.compileShadowGenerators) {
  90609. promises.push(_this._compileShadowGeneratorsAsync());
  90610. }
  90611. return Promise.all(promises).then(function () {
  90612. _this._state = BABYLON.GLTFLoaderState.Ready;
  90613. _this._startAnimations();
  90614. BABYLON.Tools.SetImmediate(function () {
  90615. if (!_this._disposed) {
  90616. Promise.all(_this._completePromises).then(function () {
  90617. _this._state = BABYLON.GLTFLoaderState.Complete;
  90618. _this.onCompleteObservable.notifyObservers(_this);
  90619. _this.onCompleteObservable.clear();
  90620. _this._clear();
  90621. }).catch(function (error) {
  90622. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90623. _this._clear();
  90624. });
  90625. }
  90626. });
  90627. });
  90628. }).catch(function (error) {
  90629. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90630. _this._clear();
  90631. throw error;
  90632. });
  90633. };
  90634. GLTFLoader.prototype._loadExtensions = function () {
  90635. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90636. var name_1 = _a[_i];
  90637. var extension = GLTFLoader._Factories[name_1](this);
  90638. this._extensions[name_1] = extension;
  90639. this.onExtensionLoadedObservable.notifyObservers(extension);
  90640. }
  90641. this.onExtensionLoadedObservable.clear();
  90642. };
  90643. GLTFLoader.prototype._loadData = function (data) {
  90644. this._gltf = data.json;
  90645. this._setupData();
  90646. if (data.bin) {
  90647. var buffers = this._gltf.buffers;
  90648. if (buffers && buffers[0] && !buffers[0].uri) {
  90649. var binaryBuffer = buffers[0];
  90650. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90651. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90652. }
  90653. binaryBuffer._data = Promise.resolve(data.bin);
  90654. }
  90655. else {
  90656. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90657. }
  90658. }
  90659. };
  90660. GLTFLoader.prototype._setupData = function () {
  90661. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90662. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90663. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90664. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90665. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90666. GLTF2.ArrayItem.Assign(this._gltf.images);
  90667. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90668. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90669. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90670. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90671. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90672. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90673. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90674. if (this._gltf.nodes) {
  90675. var nodeParents = {};
  90676. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90677. var node = _a[_i];
  90678. if (node.children) {
  90679. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90680. var index = _c[_b];
  90681. nodeParents[index] = node._index;
  90682. }
  90683. }
  90684. }
  90685. var rootNode = this._createRootNode();
  90686. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90687. var node = _e[_d];
  90688. var parentIndex = nodeParents[node._index];
  90689. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90690. }
  90691. }
  90692. };
  90693. GLTFLoader.prototype._createRootNode = function () {
  90694. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90695. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90696. switch (this.coordinateSystemMode) {
  90697. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90698. if (!this._babylonScene.useRightHandedSystem) {
  90699. rootNode.rotation = [0, 1, 0, 0];
  90700. rootNode.scale = [1, 1, -1];
  90701. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90702. }
  90703. break;
  90704. }
  90705. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90706. this._babylonScene.useRightHandedSystem = true;
  90707. break;
  90708. }
  90709. default: {
  90710. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90711. }
  90712. }
  90713. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90714. return rootNode;
  90715. };
  90716. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90717. var promises = new Array();
  90718. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90719. var node = nodes_1[_i];
  90720. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90721. }
  90722. promises.push(this._loadAnimationsAsync());
  90723. return Promise.all(promises).then(function () { });
  90724. };
  90725. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90726. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90727. if (promise) {
  90728. return promise;
  90729. }
  90730. var promises = new Array();
  90731. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90732. var index = _a[_i];
  90733. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90734. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90735. }
  90736. promises.push(this._loadAnimationsAsync());
  90737. return Promise.all(promises).then(function () { });
  90738. };
  90739. GLTFLoader.prototype._getMeshes = function () {
  90740. var meshes = new Array();
  90741. // Root mesh is always first.
  90742. meshes.push(this._rootBabylonMesh);
  90743. var nodes = this._gltf.nodes;
  90744. if (nodes) {
  90745. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  90746. var node = nodes_2[_i];
  90747. if (node._babylonMesh) {
  90748. meshes.push(node._babylonMesh);
  90749. }
  90750. }
  90751. }
  90752. return meshes;
  90753. };
  90754. GLTFLoader.prototype._getSkeletons = function () {
  90755. var skeletons = new Array();
  90756. var skins = this._gltf.skins;
  90757. if (skins) {
  90758. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  90759. var skin = skins_1[_i];
  90760. if (skin._babylonSkeleton) {
  90761. skeletons.push(skin._babylonSkeleton);
  90762. }
  90763. }
  90764. }
  90765. return skeletons;
  90766. };
  90767. GLTFLoader.prototype._startAnimations = function () {
  90768. var animations = this._gltf.animations;
  90769. if (!animations) {
  90770. return;
  90771. }
  90772. switch (this.animationStartMode) {
  90773. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  90774. // do nothing
  90775. break;
  90776. }
  90777. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  90778. var animation = animations[0];
  90779. animation._babylonAnimationGroup.start(true);
  90780. break;
  90781. }
  90782. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  90783. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  90784. var animation = animations_1[_i];
  90785. animation._babylonAnimationGroup.start(true);
  90786. }
  90787. break;
  90788. }
  90789. default: {
  90790. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  90791. return;
  90792. }
  90793. }
  90794. };
  90795. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  90796. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  90797. if (promise) {
  90798. return promise;
  90799. }
  90800. if (node._babylonMesh) {
  90801. throw new Error(context + ": Invalid recursive node hierarchy");
  90802. }
  90803. var promises = new Array();
  90804. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  90805. node._babylonMesh = babylonMesh;
  90806. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  90807. node._babylonAnimationTargets.push(babylonMesh);
  90808. GLTFLoader._LoadTransform(node, babylonMesh);
  90809. if (node.mesh != undefined) {
  90810. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  90811. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  90812. }
  90813. if (node.children) {
  90814. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90815. var index = _a[_i];
  90816. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  90817. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  90818. }
  90819. }
  90820. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  90821. return Promise.all(promises).then(function () { });
  90822. };
  90823. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  90824. // TODO: instancing
  90825. var promises = new Array();
  90826. var primitives = mesh.primitives;
  90827. if (!primitives || primitives.length === 0) {
  90828. throw new Error(context + ": Primitives are missing");
  90829. }
  90830. GLTF2.ArrayItem.Assign(primitives);
  90831. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  90832. var primitive = primitives_1[_i];
  90833. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  90834. }
  90835. if (node.skin != undefined) {
  90836. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  90837. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  90838. }
  90839. return Promise.all(promises).then(function () {
  90840. if (node._primitiveBabylonMeshes) {
  90841. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  90842. var primitiveBabylonMesh = _a[_i];
  90843. primitiveBabylonMesh._refreshBoundingInfo(true);
  90844. }
  90845. }
  90846. });
  90847. };
  90848. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  90849. var _this = this;
  90850. var promises = new Array();
  90851. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  90852. babylonMesh.setEnabled(false);
  90853. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  90854. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  90855. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  90856. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  90857. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  90858. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  90859. }));
  90860. if (primitive.material == undefined) {
  90861. babylonMesh.material = this._getDefaultMaterial();
  90862. }
  90863. else {
  90864. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  90865. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  90866. }
  90867. return Promise.all(promises).then(function () {
  90868. babylonMesh.setEnabled(true);
  90869. });
  90870. };
  90871. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  90872. var _this = this;
  90873. var attributes = primitive.attributes;
  90874. if (!attributes) {
  90875. throw new Error(context + ": Attributes are missing");
  90876. }
  90877. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  90878. // TODO: handle other primitive modes
  90879. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  90880. }
  90881. var promises = new Array();
  90882. var babylonVertexData = new BABYLON.VertexData();
  90883. if (primitive.indices == undefined) {
  90884. var positionAccessorIndex = attributes["POSITION"];
  90885. if (positionAccessorIndex != undefined) {
  90886. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  90887. babylonVertexData.indices = new Uint32Array(accessor.count);
  90888. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  90889. babylonVertexData.indices[i] = i;
  90890. }
  90891. }
  90892. }
  90893. else {
  90894. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  90895. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  90896. babylonVertexData.indices = data;
  90897. }));
  90898. }
  90899. var loadAttribute = function (attribute, kind) {
  90900. if (attributes[attribute] == undefined) {
  90901. return;
  90902. }
  90903. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  90904. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  90905. babylonMesh._delayInfo.push(kind);
  90906. }
  90907. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  90908. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  90909. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  90910. if (attribute === "COLOR_0") {
  90911. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  90912. babylonMesh.hasVertexAlpha = true;
  90913. if (accessor.type === "VEC3") {
  90914. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  90915. }
  90916. }
  90917. babylonVertexData.set(attributeData, kind);
  90918. }));
  90919. };
  90920. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  90921. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  90922. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  90923. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  90924. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  90925. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  90926. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  90927. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  90928. return Promise.all(promises).then(function () {
  90929. return babylonVertexData;
  90930. });
  90931. };
  90932. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  90933. if (!primitive.targets) {
  90934. return;
  90935. }
  90936. if (node._numMorphTargets == undefined) {
  90937. node._numMorphTargets = primitive.targets.length;
  90938. }
  90939. else if (primitive.targets.length !== node._numMorphTargets) {
  90940. throw new Error(context + ": Primitives do not have the same number of targets");
  90941. }
  90942. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  90943. for (var index = 0; index < primitive.targets.length; index++) {
  90944. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  90945. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  90946. // TODO: tell the target whether it has positions, normals, tangents
  90947. }
  90948. };
  90949. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  90950. if (!primitive.targets) {
  90951. return Promise.resolve();
  90952. }
  90953. var promises = new Array();
  90954. var morphTargetManager = babylonMesh.morphTargetManager;
  90955. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  90956. var babylonMorphTarget = morphTargetManager.getTarget(index);
  90957. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  90958. }
  90959. return Promise.all(promises).then(function () { });
  90960. };
  90961. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  90962. var _this = this;
  90963. var promises = new Array();
  90964. var loadAttribute = function (attribute, setData) {
  90965. if (attributes[attribute] == undefined) {
  90966. return;
  90967. }
  90968. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  90969. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  90970. setData(data);
  90971. }));
  90972. };
  90973. loadAttribute("POSITION", function (data) {
  90974. if (babylonVertexData.positions) {
  90975. for (var i = 0; i < data.length; i++) {
  90976. data[i] += babylonVertexData.positions[i];
  90977. }
  90978. babylonMorphTarget.setPositions(data);
  90979. }
  90980. });
  90981. loadAttribute("NORMAL", function (data) {
  90982. if (babylonVertexData.normals) {
  90983. for (var i = 0; i < data.length; i++) {
  90984. data[i] += babylonVertexData.normals[i];
  90985. }
  90986. babylonMorphTarget.setNormals(data);
  90987. }
  90988. });
  90989. loadAttribute("TANGENT", function (data) {
  90990. if (babylonVertexData.tangents) {
  90991. // Tangent data for morph targets is stored as xyz delta.
  90992. // The vertexData.tangent is stored as xyzw.
  90993. // So we need to skip every fourth vertexData.tangent.
  90994. for (var i = 0, j = 0; i < data.length; i++) {
  90995. data[i] += babylonVertexData.tangents[j++];
  90996. if ((i + 1) % 3 == 0) {
  90997. j++;
  90998. }
  90999. }
  91000. babylonMorphTarget.setTangents(data);
  91001. }
  91002. });
  91003. return Promise.all(promises).then(function () { });
  91004. };
  91005. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91006. if (accessor.componentType == 5126 /* FLOAT */) {
  91007. return data;
  91008. }
  91009. var factor = 1;
  91010. if (accessor.normalized) {
  91011. switch (accessor.componentType) {
  91012. case 5121 /* UNSIGNED_BYTE */: {
  91013. factor = 1 / 255;
  91014. break;
  91015. }
  91016. case 5123 /* UNSIGNED_SHORT */: {
  91017. factor = 1 / 65535;
  91018. break;
  91019. }
  91020. default: {
  91021. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91022. }
  91023. }
  91024. }
  91025. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91026. for (var i = 0; i < result.length; i++) {
  91027. result[i] = data[i] * factor;
  91028. }
  91029. return result;
  91030. };
  91031. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91032. var result = new Float32Array(data.length / 3 * 4);
  91033. var offset = 0;
  91034. for (var i = 0; i < result.length; i++) {
  91035. if ((i + 1) % 4 === 0) {
  91036. result[i] = 1;
  91037. }
  91038. else {
  91039. result[i] = data[offset++];
  91040. }
  91041. }
  91042. return result;
  91043. };
  91044. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91045. var position = BABYLON.Vector3.Zero();
  91046. var rotation = BABYLON.Quaternion.Identity();
  91047. var scaling = BABYLON.Vector3.One();
  91048. if (node.matrix) {
  91049. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91050. matrix.decompose(scaling, rotation, position);
  91051. }
  91052. else {
  91053. if (node.translation)
  91054. position = BABYLON.Vector3.FromArray(node.translation);
  91055. if (node.rotation)
  91056. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91057. if (node.scale)
  91058. scaling = BABYLON.Vector3.FromArray(node.scale);
  91059. }
  91060. babylonNode.position = position;
  91061. babylonNode.rotationQuaternion = rotation;
  91062. babylonNode.scaling = scaling;
  91063. };
  91064. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91065. var _this = this;
  91066. var assignSkeleton = function () {
  91067. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91068. var babylonMesh = _a[_i];
  91069. babylonMesh.skeleton = skin._babylonSkeleton;
  91070. }
  91071. node._babylonMesh.parent = _this._rootBabylonMesh;
  91072. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91073. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91074. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91075. };
  91076. if (skin._loaded) {
  91077. assignSkeleton();
  91078. return skin._loaded;
  91079. }
  91080. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91081. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91082. var skeletonId = "skeleton" + skin._index;
  91083. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91084. skin._babylonSkeleton = babylonSkeleton;
  91085. _this._loadBones(context, skin, inverseBindMatricesData);
  91086. assignSkeleton();
  91087. }));
  91088. };
  91089. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91090. if (skin.inverseBindMatrices == undefined) {
  91091. return Promise.resolve(null);
  91092. }
  91093. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91094. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91095. return data;
  91096. });
  91097. };
  91098. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91099. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91100. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91101. node._babylonAnimationTargets.push(babylonBone);
  91102. return babylonBone;
  91103. };
  91104. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91105. var babylonBones = {};
  91106. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91107. var index = _a[_i];
  91108. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91109. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91110. }
  91111. };
  91112. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91113. var babylonBone = babylonBones[node._index];
  91114. if (babylonBone) {
  91115. return babylonBone;
  91116. }
  91117. var boneIndex = skin.joints.indexOf(node._index);
  91118. var baseMatrix = BABYLON.Matrix.Identity();
  91119. if (inverseBindMatricesData && boneIndex !== -1) {
  91120. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91121. baseMatrix.invertToRef(baseMatrix);
  91122. }
  91123. var babylonParentBone = null;
  91124. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91125. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91126. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91127. }
  91128. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91129. babylonBones[node._index] = babylonBone;
  91130. return babylonBone;
  91131. };
  91132. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91133. return node.matrix ?
  91134. BABYLON.Matrix.FromArray(node.matrix) :
  91135. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  91136. };
  91137. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91138. var animations = this._gltf.animations;
  91139. if (!animations) {
  91140. return Promise.resolve();
  91141. }
  91142. var promises = new Array();
  91143. for (var index = 0; index < animations.length; index++) {
  91144. var animation = animations[index];
  91145. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91146. }
  91147. return Promise.all(promises).then(function () { });
  91148. };
  91149. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91150. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91151. animation._babylonAnimationGroup = babylonAnimationGroup;
  91152. var promises = new Array();
  91153. GLTF2.ArrayItem.Assign(animation.channels);
  91154. GLTF2.ArrayItem.Assign(animation.samplers);
  91155. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91156. var channel = _a[_i];
  91157. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91158. }
  91159. return Promise.all(promises).then(function () {
  91160. babylonAnimationGroup.normalize();
  91161. });
  91162. };
  91163. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91164. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91165. if (!targetNode._babylonMesh) {
  91166. return Promise.resolve();
  91167. }
  91168. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91169. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91170. var targetPath;
  91171. var animationType;
  91172. switch (channel.target.path) {
  91173. case "translation" /* TRANSLATION */: {
  91174. targetPath = "position";
  91175. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91176. break;
  91177. }
  91178. case "rotation" /* ROTATION */: {
  91179. targetPath = "rotationQuaternion";
  91180. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91181. break;
  91182. }
  91183. case "scale" /* SCALE */: {
  91184. targetPath = "scaling";
  91185. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91186. break;
  91187. }
  91188. case "weights" /* WEIGHTS */: {
  91189. targetPath = "influence";
  91190. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91191. break;
  91192. }
  91193. default: {
  91194. throw new Error(context + ": Invalid target path " + channel.target.path);
  91195. }
  91196. }
  91197. var outputBufferOffset = 0;
  91198. var getNextOutputValue;
  91199. switch (targetPath) {
  91200. case "position": {
  91201. getNextOutputValue = function () {
  91202. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91203. outputBufferOffset += 3;
  91204. return value;
  91205. };
  91206. break;
  91207. }
  91208. case "rotationQuaternion": {
  91209. getNextOutputValue = function () {
  91210. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91211. outputBufferOffset += 4;
  91212. return value;
  91213. };
  91214. break;
  91215. }
  91216. case "scaling": {
  91217. getNextOutputValue = function () {
  91218. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91219. outputBufferOffset += 3;
  91220. return value;
  91221. };
  91222. break;
  91223. }
  91224. case "influence": {
  91225. getNextOutputValue = function () {
  91226. var value = new Array(targetNode._numMorphTargets);
  91227. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91228. value[i] = data.output[outputBufferOffset++];
  91229. }
  91230. return value;
  91231. };
  91232. break;
  91233. }
  91234. }
  91235. var getNextKey;
  91236. switch (data.interpolation) {
  91237. case "STEP" /* STEP */: {
  91238. getNextKey = function (frameIndex) { return ({
  91239. frame: data.input[frameIndex],
  91240. value: getNextOutputValue(),
  91241. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91242. }); };
  91243. break;
  91244. }
  91245. case "LINEAR" /* LINEAR */: {
  91246. getNextKey = function (frameIndex) { return ({
  91247. frame: data.input[frameIndex],
  91248. value: getNextOutputValue()
  91249. }); };
  91250. break;
  91251. }
  91252. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91253. getNextKey = function (frameIndex) { return ({
  91254. frame: data.input[frameIndex],
  91255. inTangent: getNextOutputValue(),
  91256. value: getNextOutputValue(),
  91257. outTangent: getNextOutputValue()
  91258. }); };
  91259. break;
  91260. }
  91261. }
  91262. var keys;
  91263. if (data.input.length === 1) {
  91264. var key = getNextKey(0);
  91265. keys = [
  91266. { frame: key.frame, value: key.value },
  91267. { frame: key.frame + 1, value: key.value }
  91268. ];
  91269. }
  91270. else {
  91271. keys = new Array(data.input.length);
  91272. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91273. keys[frameIndex] = getNextKey(frameIndex);
  91274. }
  91275. }
  91276. if (targetPath === "influence") {
  91277. var _loop_1 = function (targetIndex) {
  91278. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91279. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91280. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91281. frame: key.frame,
  91282. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91283. value: key.value[targetIndex],
  91284. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91285. }); }));
  91286. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91287. var babylonMesh = _a[_i];
  91288. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91289. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91290. }
  91291. };
  91292. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91293. _loop_1(targetIndex);
  91294. }
  91295. }
  91296. else {
  91297. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91298. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91299. babylonAnimation.setKeys(keys);
  91300. if (targetNode._babylonAnimationTargets) {
  91301. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91302. var target = _a[_i];
  91303. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91304. }
  91305. }
  91306. }
  91307. });
  91308. };
  91309. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91310. if (sampler._data) {
  91311. return sampler._data;
  91312. }
  91313. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91314. switch (interpolation) {
  91315. case "STEP" /* STEP */:
  91316. case "LINEAR" /* LINEAR */:
  91317. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91318. break;
  91319. }
  91320. default: {
  91321. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91322. }
  91323. }
  91324. var inputData;
  91325. var outputData;
  91326. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91327. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91328. sampler._data = Promise.all([
  91329. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91330. inputData = data;
  91331. }),
  91332. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91333. outputData = data;
  91334. })
  91335. ]).then(function () {
  91336. return {
  91337. input: inputData,
  91338. interpolation: interpolation,
  91339. output: outputData,
  91340. };
  91341. });
  91342. return sampler._data;
  91343. };
  91344. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91345. if (buffer._data) {
  91346. return buffer._data;
  91347. }
  91348. if (!buffer.uri) {
  91349. throw new Error(context + ": Uri is missing");
  91350. }
  91351. buffer._data = this._loadUriAsync(context, buffer.uri);
  91352. return buffer._data;
  91353. };
  91354. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91355. if (bufferView._data) {
  91356. return bufferView._data;
  91357. }
  91358. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91359. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91360. try {
  91361. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91362. }
  91363. catch (e) {
  91364. throw new Error(context + ": " + e.message);
  91365. }
  91366. });
  91367. return bufferView._data;
  91368. };
  91369. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91370. var _this = this;
  91371. if (accessor.sparse) {
  91372. throw new Error(context + ": Sparse accessors are not currently supported");
  91373. }
  91374. if (accessor._data) {
  91375. return accessor._data;
  91376. }
  91377. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91378. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91379. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91380. var byteOffset = accessor.byteOffset || 0;
  91381. var byteStride = bufferView.byteStride;
  91382. if (byteStride === 0) {
  91383. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91384. }
  91385. try {
  91386. switch (accessor.componentType) {
  91387. case 5120 /* BYTE */: {
  91388. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91389. }
  91390. case 5121 /* UNSIGNED_BYTE */: {
  91391. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91392. }
  91393. case 5122 /* SHORT */: {
  91394. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91395. }
  91396. case 5123 /* UNSIGNED_SHORT */: {
  91397. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91398. }
  91399. case 5125 /* UNSIGNED_INT */: {
  91400. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91401. }
  91402. case 5126 /* FLOAT */: {
  91403. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91404. }
  91405. default: {
  91406. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91407. }
  91408. }
  91409. }
  91410. catch (e) {
  91411. throw new Error(context + ": " + e);
  91412. }
  91413. });
  91414. return accessor._data;
  91415. };
  91416. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91417. byteOffset += data.byteOffset;
  91418. var targetLength = count * numComponents;
  91419. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91420. return new typedArray(data.buffer, byteOffset, targetLength);
  91421. }
  91422. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91423. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91424. var targetBuffer = new typedArray(targetLength);
  91425. var sourceIndex = 0;
  91426. var targetIndex = 0;
  91427. while (targetIndex < targetLength) {
  91428. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91429. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91430. targetIndex++;
  91431. }
  91432. sourceIndex += elementStride;
  91433. }
  91434. return targetBuffer;
  91435. };
  91436. GLTFLoader.prototype._getDefaultMaterial = function () {
  91437. var id = "__gltf_default";
  91438. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91439. if (!babylonMaterial) {
  91440. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91441. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91442. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91443. babylonMaterial.metallic = 1;
  91444. babylonMaterial.roughness = 1;
  91445. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91446. }
  91447. return babylonMaterial;
  91448. };
  91449. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91450. var promises = new Array();
  91451. var babylonMaterial = material._babylonMaterial;
  91452. // Ensure metallic workflow
  91453. babylonMaterial.metallic = 1;
  91454. babylonMaterial.roughness = 1;
  91455. var properties = material.pbrMetallicRoughness;
  91456. if (properties) {
  91457. if (properties.baseColorFactor) {
  91458. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91459. babylonMaterial.alpha = properties.baseColorFactor[3];
  91460. }
  91461. else {
  91462. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91463. }
  91464. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91465. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91466. if (properties.baseColorTexture) {
  91467. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91468. babylonMaterial.albedoTexture = texture;
  91469. }));
  91470. }
  91471. if (properties.metallicRoughnessTexture) {
  91472. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91473. babylonMaterial.metallicTexture = texture;
  91474. }));
  91475. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91476. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91477. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91478. }
  91479. }
  91480. this._loadMaterialAlphaProperties(context, material);
  91481. return Promise.all(promises).then(function () { });
  91482. };
  91483. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91484. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91485. if (promise) {
  91486. return promise;
  91487. }
  91488. material._babylonMeshes = material._babylonMeshes || [];
  91489. material._babylonMeshes.push(babylonMesh);
  91490. if (material._loaded) {
  91491. babylonMesh.material = material._babylonMaterial;
  91492. return material._loaded;
  91493. }
  91494. var promises = new Array();
  91495. var babylonMaterial = this._createMaterial(material);
  91496. material._babylonMaterial = babylonMaterial;
  91497. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91498. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91499. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91500. babylonMesh.material = babylonMaterial;
  91501. return (material._loaded = Promise.all(promises).then(function () { }));
  91502. };
  91503. GLTFLoader.prototype._createMaterial = function (material) {
  91504. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91505. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91506. return babylonMaterial;
  91507. };
  91508. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91509. var promises = new Array();
  91510. var babylonMaterial = material._babylonMaterial;
  91511. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91512. if (material.doubleSided) {
  91513. babylonMaterial.backFaceCulling = false;
  91514. babylonMaterial.twoSidedLighting = true;
  91515. }
  91516. if (material.normalTexture) {
  91517. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91518. babylonMaterial.bumpTexture = texture;
  91519. }));
  91520. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91521. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91522. if (material.normalTexture.scale != undefined) {
  91523. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91524. }
  91525. }
  91526. if (material.occlusionTexture) {
  91527. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91528. babylonMaterial.ambientTexture = texture;
  91529. }));
  91530. babylonMaterial.useAmbientInGrayScale = true;
  91531. if (material.occlusionTexture.strength != undefined) {
  91532. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91533. }
  91534. }
  91535. if (material.emissiveTexture) {
  91536. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91537. babylonMaterial.emissiveTexture = texture;
  91538. }));
  91539. }
  91540. return Promise.all(promises).then(function () { });
  91541. };
  91542. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91543. var babylonMaterial = material._babylonMaterial;
  91544. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91545. switch (alphaMode) {
  91546. case "OPAQUE" /* OPAQUE */: {
  91547. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91548. break;
  91549. }
  91550. case "MASK" /* MASK */: {
  91551. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91552. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91553. if (babylonMaterial.alpha) {
  91554. if (babylonMaterial.alpha === 0) {
  91555. babylonMaterial.alphaCutOff = 1;
  91556. }
  91557. else {
  91558. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91559. }
  91560. babylonMaterial.alpha = 1;
  91561. }
  91562. if (babylonMaterial.albedoTexture) {
  91563. babylonMaterial.albedoTexture.hasAlpha = true;
  91564. }
  91565. break;
  91566. }
  91567. case "BLEND" /* BLEND */: {
  91568. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91569. if (babylonMaterial.albedoTexture) {
  91570. babylonMaterial.albedoTexture.hasAlpha = true;
  91571. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91572. }
  91573. break;
  91574. }
  91575. default: {
  91576. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91577. }
  91578. }
  91579. };
  91580. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91581. var _this = this;
  91582. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91583. context = "#/textures/" + textureInfo.index;
  91584. var promises = new Array();
  91585. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91586. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91587. var deferred = new BABYLON.Deferred();
  91588. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91589. if (!_this._disposed) {
  91590. deferred.resolve();
  91591. }
  91592. }, function (message, exception) {
  91593. if (!_this._disposed) {
  91594. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91595. }
  91596. });
  91597. promises.push(deferred.promise);
  91598. babylonTexture.name = texture.name || "texture" + texture._index;
  91599. babylonTexture.wrapU = samplerData.wrapU;
  91600. babylonTexture.wrapV = samplerData.wrapV;
  91601. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91602. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91603. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91604. babylonTexture.updateURL(objectURL);
  91605. }));
  91606. assign(babylonTexture);
  91607. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91608. return Promise.all(promises).then(function () { });
  91609. };
  91610. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91611. if (!sampler._data) {
  91612. sampler._data = {
  91613. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91614. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91615. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91616. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91617. };
  91618. }
  91619. ;
  91620. return sampler._data;
  91621. };
  91622. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91623. if (image._objectURL) {
  91624. return image._objectURL;
  91625. }
  91626. var promise;
  91627. if (image.uri) {
  91628. promise = this._loadUriAsync(context, image.uri);
  91629. }
  91630. else {
  91631. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91632. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91633. }
  91634. image._objectURL = promise.then(function (data) {
  91635. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91636. });
  91637. return image._objectURL;
  91638. };
  91639. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91640. var _this = this;
  91641. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91642. if (promise) {
  91643. return promise;
  91644. }
  91645. if (!GLTFLoader._ValidateUri(uri)) {
  91646. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91647. }
  91648. if (BABYLON.Tools.IsBase64(uri)) {
  91649. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91650. }
  91651. return new Promise(function (resolve, reject) {
  91652. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91653. if (!_this._disposed) {
  91654. resolve(new Uint8Array(data));
  91655. }
  91656. }, function (event) {
  91657. if (!_this._disposed) {
  91658. try {
  91659. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91660. request._lengthComputable = event.lengthComputable;
  91661. request._loaded = event.loaded;
  91662. request._total = event.total;
  91663. _this._onProgress();
  91664. }
  91665. }
  91666. catch (e) {
  91667. reject(e);
  91668. }
  91669. }
  91670. }, _this._babylonScene.database, true, function (request, exception) {
  91671. if (!_this._disposed) {
  91672. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91673. }
  91674. });
  91675. _this._requests.push(request);
  91676. });
  91677. };
  91678. GLTFLoader.prototype._onProgress = function () {
  91679. if (!this._progressCallback) {
  91680. return;
  91681. }
  91682. var lengthComputable = true;
  91683. var loaded = 0;
  91684. var total = 0;
  91685. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91686. var request = _a[_i];
  91687. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91688. return;
  91689. }
  91690. lengthComputable = lengthComputable && request._lengthComputable;
  91691. loaded += request._loaded;
  91692. total += request._total;
  91693. }
  91694. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91695. };
  91696. GLTFLoader._GetProperty = function (context, array, index) {
  91697. if (!array || index == undefined || !array[index]) {
  91698. throw new Error(context + ": Failed to find index " + index);
  91699. }
  91700. return array[index];
  91701. };
  91702. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91703. // Set defaults if undefined
  91704. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91705. switch (mode) {
  91706. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91707. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91708. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91709. default:
  91710. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91711. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91712. }
  91713. };
  91714. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91715. // Set defaults if undefined
  91716. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91717. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91718. if (magFilter === 9729 /* LINEAR */) {
  91719. switch (minFilter) {
  91720. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91721. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91722. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91723. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91724. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91725. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91726. default:
  91727. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91728. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91729. }
  91730. }
  91731. else {
  91732. if (magFilter !== 9728 /* NEAREST */) {
  91733. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91734. }
  91735. switch (minFilter) {
  91736. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91737. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91738. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91739. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91740. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  91741. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  91742. default:
  91743. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91744. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91745. }
  91746. }
  91747. };
  91748. GLTFLoader._GetNumComponents = function (context, type) {
  91749. switch (type) {
  91750. case "SCALAR": return 1;
  91751. case "VEC2": return 2;
  91752. case "VEC3": return 3;
  91753. case "VEC4": return 4;
  91754. case "MAT2": return 4;
  91755. case "MAT3": return 9;
  91756. case "MAT4": return 16;
  91757. }
  91758. throw new Error(context + ": Invalid type " + type);
  91759. };
  91760. GLTFLoader._ValidateUri = function (uri) {
  91761. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  91762. };
  91763. GLTFLoader.prototype._compileMaterialsAsync = function () {
  91764. var promises = new Array();
  91765. if (this._gltf.materials) {
  91766. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  91767. var material = _a[_i];
  91768. var babylonMaterial = material._babylonMaterial;
  91769. var babylonMeshes = material._babylonMeshes;
  91770. if (babylonMaterial && babylonMeshes) {
  91771. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  91772. var babylonMesh = babylonMeshes_1[_b];
  91773. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  91774. if (this.useClipPlane) {
  91775. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  91776. }
  91777. }
  91778. }
  91779. }
  91780. }
  91781. return Promise.all(promises).then(function () { });
  91782. };
  91783. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  91784. var promises = new Array();
  91785. var lights = this._babylonScene.lights;
  91786. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91787. var light = lights_1[_i];
  91788. var generator = light.getShadowGenerator();
  91789. if (generator) {
  91790. promises.push(generator.forceCompilationAsync());
  91791. }
  91792. }
  91793. return Promise.all(promises).then(function () { });
  91794. };
  91795. GLTFLoader.prototype._clear = function () {
  91796. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91797. var request = _a[_i];
  91798. request.abort();
  91799. }
  91800. this._requests.length = 0;
  91801. if (this._gltf && this._gltf.images) {
  91802. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  91803. var image = _c[_b];
  91804. if (image._objectURL) {
  91805. image._objectURL.then(function (value) {
  91806. URL.revokeObjectURL(value);
  91807. });
  91808. image._objectURL = undefined;
  91809. }
  91810. }
  91811. }
  91812. delete this._gltf;
  91813. delete this._babylonScene;
  91814. this._completePromises.length = 0;
  91815. this._extensions = {};
  91816. delete this._rootBabylonMesh;
  91817. delete this._progressCallback;
  91818. this.onMeshLoadedObservable.clear();
  91819. this.onTextureLoadedObservable.clear();
  91820. this.onMaterialLoadedObservable.clear();
  91821. };
  91822. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  91823. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91824. var name_2 = _a[_i];
  91825. var extension = this._extensions[name_2];
  91826. if (extension.enabled) {
  91827. var promise = actionAsync(extension);
  91828. if (promise) {
  91829. return promise;
  91830. }
  91831. }
  91832. }
  91833. return null;
  91834. };
  91835. GLTFLoader._Names = new Array();
  91836. GLTFLoader._Factories = {};
  91837. return GLTFLoader;
  91838. }());
  91839. GLTF2.GLTFLoader = GLTFLoader;
  91840. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91841. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91842. })(BABYLON || (BABYLON = {}));
  91843. //# sourceMappingURL=babylon.glTFLoader.js.map
  91844. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91845. var BABYLON;
  91846. (function (BABYLON) {
  91847. var GLTF2;
  91848. (function (GLTF2) {
  91849. var GLTFLoaderExtension = /** @class */ (function () {
  91850. function GLTFLoaderExtension(loader) {
  91851. this.enabled = true;
  91852. this._loader = loader;
  91853. }
  91854. // #region Overridable Methods
  91855. /** Override this method to modify the default behavior for loading scenes. */
  91856. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  91857. /** Override this method to modify the default behavior for loading nodes. */
  91858. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  91859. /** Override this method to modify the default behavior for loading materials. */
  91860. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  91861. /** Override this method to modify the default behavior for loading uris. */
  91862. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  91863. // #endregion
  91864. /** Helper method called by a loader extension to load an glTF extension. */
  91865. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  91866. var _this = this;
  91867. if (!property.extensions) {
  91868. return null;
  91869. }
  91870. var extensions = property.extensions;
  91871. var extension = extensions[this.name];
  91872. if (!extension) {
  91873. return null;
  91874. }
  91875. // Clear out the extension before executing the action to avoid recursing into the same property.
  91876. delete extensions[this.name];
  91877. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  91878. // Restore the extension after completing the action.
  91879. extensions[_this.name] = extension;
  91880. });
  91881. };
  91882. /** Helper method called by the loader to allow extensions to override loading scenes. */
  91883. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  91884. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  91885. };
  91886. /** Helper method called by the loader to allow extensions to override loading nodes. */
  91887. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  91888. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  91889. };
  91890. /** Helper method called by the loader to allow extensions to override loading materials. */
  91891. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  91892. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  91893. };
  91894. /** Helper method called by the loader to allow extensions to override loading uris. */
  91895. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  91896. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  91897. };
  91898. return GLTFLoaderExtension;
  91899. }());
  91900. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  91901. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91902. })(BABYLON || (BABYLON = {}));
  91903. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91904. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91905. var BABYLON;
  91906. (function (BABYLON) {
  91907. var GLTF2;
  91908. (function (GLTF2) {
  91909. var Extensions;
  91910. (function (Extensions) {
  91911. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  91912. var NAME = "MSFT_lod";
  91913. var MSFT_lod = /** @class */ (function (_super) {
  91914. __extends(MSFT_lod, _super);
  91915. function MSFT_lod() {
  91916. var _this = _super !== null && _super.apply(this, arguments) || this;
  91917. _this.name = NAME;
  91918. /**
  91919. * Maximum number of LODs to load, starting from the lowest LOD.
  91920. */
  91921. _this.maxLODsToLoad = Number.MAX_VALUE;
  91922. _this._loadingNodeLOD = null;
  91923. _this._loadNodeSignals = {};
  91924. _this._loadingMaterialLOD = null;
  91925. _this._loadMaterialSignals = {};
  91926. return _this;
  91927. }
  91928. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  91929. var _this = this;
  91930. return this._loadExtensionAsync(context, node, function (context, extension) {
  91931. var firstPromise;
  91932. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  91933. var _loop_1 = function (indexLOD) {
  91934. var nodeLOD = nodeLODs[indexLOD];
  91935. if (indexLOD !== 0) {
  91936. _this._loadingNodeLOD = nodeLOD;
  91937. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  91938. }
  91939. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  91940. if (indexLOD !== 0) {
  91941. var previousNodeLOD = nodeLODs[indexLOD - 1];
  91942. previousNodeLOD._babylonMesh.setEnabled(false);
  91943. }
  91944. if (indexLOD !== nodeLODs.length - 1) {
  91945. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  91946. _this._loadNodeSignals[nodeIndex].resolve();
  91947. delete _this._loadNodeSignals[nodeIndex];
  91948. }
  91949. });
  91950. if (indexLOD === 0) {
  91951. firstPromise = promise;
  91952. }
  91953. else {
  91954. _this._loader._completePromises.push(promise);
  91955. _this._loadingNodeLOD = null;
  91956. }
  91957. };
  91958. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  91959. _loop_1(indexLOD);
  91960. }
  91961. return firstPromise;
  91962. });
  91963. };
  91964. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91965. var _this = this;
  91966. // Don't load material LODs if already loading a node LOD.
  91967. if (this._loadingNodeLOD) {
  91968. return null;
  91969. }
  91970. return this._loadExtensionAsync(context, material, function (context, extension) {
  91971. var firstPromise;
  91972. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  91973. var _loop_2 = function (indexLOD) {
  91974. var materialLOD = materialLODs[indexLOD];
  91975. if (indexLOD !== 0) {
  91976. _this._loadingMaterialLOD = materialLOD;
  91977. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  91978. }
  91979. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  91980. if (indexLOD !== materialLODs.length - 1) {
  91981. var materialIndex = materialLODs[indexLOD + 1]._index;
  91982. _this._loadMaterialSignals[materialIndex].resolve();
  91983. delete _this._loadMaterialSignals[materialIndex];
  91984. }
  91985. });
  91986. if (indexLOD === 0) {
  91987. firstPromise = promise;
  91988. }
  91989. else {
  91990. _this._loader._completePromises.push(promise);
  91991. _this._loadingMaterialLOD = null;
  91992. }
  91993. };
  91994. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  91995. _loop_2(indexLOD);
  91996. }
  91997. return firstPromise;
  91998. });
  91999. };
  92000. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92001. var _this = this;
  92002. // Defer the loading of uris if loading a material or node LOD.
  92003. if (this._loadingMaterialLOD) {
  92004. var index = this._loadingMaterialLOD._index;
  92005. return this._loadMaterialSignals[index].promise.then(function () {
  92006. return _this._loader._loadUriAsync(context, uri);
  92007. });
  92008. }
  92009. else if (this._loadingNodeLOD) {
  92010. var index = this._loadingNodeLOD._index;
  92011. return this._loadNodeSignals[index].promise.then(function () {
  92012. return _this._loader._loadUriAsync(context, uri);
  92013. });
  92014. }
  92015. return null;
  92016. };
  92017. /**
  92018. * Gets an array of LOD properties from lowest to highest.
  92019. */
  92020. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92021. if (this.maxLODsToLoad <= 0) {
  92022. throw new Error("maxLODsToLoad must be greater than zero");
  92023. }
  92024. var properties = new Array();
  92025. for (var i = ids.length - 1; i >= 0; i--) {
  92026. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92027. if (properties.length === this.maxLODsToLoad) {
  92028. return properties;
  92029. }
  92030. }
  92031. properties.push(property);
  92032. return properties;
  92033. };
  92034. return MSFT_lod;
  92035. }(GLTF2.GLTFLoaderExtension));
  92036. Extensions.MSFT_lod = MSFT_lod;
  92037. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92038. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92039. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92040. })(BABYLON || (BABYLON = {}));
  92041. //# sourceMappingURL=MSFT_lod.js.map
  92042. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92043. var BABYLON;
  92044. (function (BABYLON) {
  92045. var GLTF2;
  92046. (function (GLTF2) {
  92047. var Extensions;
  92048. (function (Extensions) {
  92049. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92050. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92051. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92052. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92053. function KHR_materials_pbrSpecularGlossiness() {
  92054. var _this = _super !== null && _super.apply(this, arguments) || this;
  92055. _this.name = NAME;
  92056. return _this;
  92057. }
  92058. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92059. var _this = this;
  92060. return this._loadExtensionAsync(context, material, function (context, extension) {
  92061. material._babylonMeshes = material._babylonMeshes || [];
  92062. material._babylonMeshes.push(babylonMesh);
  92063. if (material._loaded) {
  92064. babylonMesh.material = material._babylonMaterial;
  92065. return material._loaded;
  92066. }
  92067. var promises = new Array();
  92068. var babylonMaterial = _this._loader._createMaterial(material);
  92069. material._babylonMaterial = babylonMaterial;
  92070. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92071. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92072. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92073. babylonMesh.material = babylonMaterial;
  92074. return (material._loaded = Promise.all(promises).then(function () { }));
  92075. });
  92076. };
  92077. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92078. var promises = new Array();
  92079. var babylonMaterial = material._babylonMaterial;
  92080. if (properties.diffuseFactor) {
  92081. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92082. babylonMaterial.alpha = properties.diffuseFactor[3];
  92083. }
  92084. else {
  92085. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92086. }
  92087. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92088. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92089. if (properties.diffuseTexture) {
  92090. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92091. babylonMaterial.albedoTexture = texture;
  92092. }));
  92093. }
  92094. if (properties.specularGlossinessTexture) {
  92095. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92096. babylonMaterial.reflectivityTexture = texture;
  92097. }));
  92098. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92099. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92100. }
  92101. loader._loadMaterialAlphaProperties(context, material);
  92102. return Promise.all(promises).then(function () { });
  92103. };
  92104. return KHR_materials_pbrSpecularGlossiness;
  92105. }(GLTF2.GLTFLoaderExtension));
  92106. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92107. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92108. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92109. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92110. })(BABYLON || (BABYLON = {}));
  92111. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92112. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92113. var BABYLON;
  92114. (function (BABYLON) {
  92115. var GLTF2;
  92116. (function (GLTF2) {
  92117. var Extensions;
  92118. (function (Extensions) {
  92119. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92120. var NAME = "KHR_lights";
  92121. var LightType;
  92122. (function (LightType) {
  92123. LightType["AMBIENT"] = "ambient";
  92124. LightType["DIRECTIONAL"] = "directional";
  92125. LightType["POINT"] = "point";
  92126. LightType["SPOT"] = "spot";
  92127. })(LightType || (LightType = {}));
  92128. var KHR_lights = /** @class */ (function (_super) {
  92129. __extends(KHR_lights, _super);
  92130. function KHR_lights() {
  92131. var _this = _super !== null && _super.apply(this, arguments) || this;
  92132. _this.name = NAME;
  92133. return _this;
  92134. }
  92135. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92136. var _this = this;
  92137. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92138. var promise = _this._loader._loadSceneAsync(context, scene);
  92139. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92140. if (light.type !== LightType.AMBIENT) {
  92141. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92142. }
  92143. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92144. return promise;
  92145. });
  92146. };
  92147. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92148. var _this = this;
  92149. return this._loadExtensionAsync(context, node, function (context, extension) {
  92150. var promise = _this._loader._loadNodeAsync(context, node);
  92151. var babylonLight;
  92152. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92153. var name = node._babylonMesh.name;
  92154. switch (light.type) {
  92155. case LightType.AMBIENT: {
  92156. throw new Error(context + ": Ambient lights are not allowed on a node");
  92157. }
  92158. case LightType.DIRECTIONAL: {
  92159. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92160. break;
  92161. }
  92162. case LightType.POINT: {
  92163. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92164. break;
  92165. }
  92166. case LightType.SPOT: {
  92167. var spotLight = light;
  92168. // TODO: support inner and outer cone angles
  92169. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92170. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92171. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92172. break;
  92173. }
  92174. default: {
  92175. throw new Error(context + ": Invalid light type " + light.type);
  92176. }
  92177. }
  92178. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92179. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92180. babylonLight.parent = node._babylonMesh;
  92181. return promise;
  92182. });
  92183. };
  92184. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92185. get: function () {
  92186. var extensions = this._loader._gltf.extensions;
  92187. if (!extensions || !extensions[this.name]) {
  92188. throw new Error("#/extensions: " + this.name + " not found");
  92189. }
  92190. var extension = extensions[this.name];
  92191. return extension.lights;
  92192. },
  92193. enumerable: true,
  92194. configurable: true
  92195. });
  92196. return KHR_lights;
  92197. }(GLTF2.GLTFLoaderExtension));
  92198. Extensions.KHR_lights = KHR_lights;
  92199. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92200. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92201. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92202. })(BABYLON || (BABYLON = {}));
  92203. //# sourceMappingURL=KHR_lights.js.map
  92204. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92205. globalObject["BABYLON"] = BABYLON;
  92206. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var 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 Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92207. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,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,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };